Google questions

Shortest Cycle Through a Node

GoogleOnsiteMedium

You are given a directed graph with n nodes numbered 0 to n - 1, and a list edges where [a, b] is an edge from a to b. The same edge can appear more than once in edges.

Part 1: Shortest cycle through one node

A cycle through v is a walk that starts at v, follows edges, and returns to v. Its length is the number of edges it uses. A self-loop [v, v] counts as a cycle of length 1.

Return the length of the shortest cycle through node v, or -1 if no cycle passes through it. Cycles that do not pass through v do not count.

  1. Example 1
    n
    3
    v
    0
    edges
    [[0,1],[1,2],[2,0]]
    Output
    3

    Why: The edges 0 -> 1, 1 -> 2 and 2 -> 0 form a cycle of 3 edges through node 0.

  2. Example 2
    n
    3
    v
    0
    edges
    [[0,1],[1,2]]
    Output
    -1

    Why: Edges only go forward, so no walk from node 0 ever returns to it.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= a < n and 0 <= b < n for every edge [a, b]
  • 0 <= v < n
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question