FastPrepShortest Directed Cycle Through a Start Node

Shortest Directed Cycle Through a Start Node

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

A directed graph has nodeCount nodes numbered from 0 through nodeCount - 1 and directed edges [from, to].

Given start, return the number of edges in the shortest directed cycle that begins at start and returns to start. Return -1 when no such cycle exists.

A self-loop [start, start] is a cycle of length 1.

Function

shortestCycleFromStart(nodeCount: int, edges: int[][], start: int) → int

Examples

Example 1

nodeCount = 4edges = [[0,1],[1,2],[2,0],[1,3]]start = 0return = 3

Cycle 0→1→2→0 has three edges.

Example 2

nodeCount = 3edges = [[0,0],[0,1],[1,0]]start = 0return = 1

The self-loop is shorter than cycle 0→1→0.

Example 3

nodeCount = 4edges = [[0,1],[1,2],[2,3]]start = 0return = -1

No directed path returns to node 0.

Constraints

  • 1 <= nodeCount <= 100000.
  • 0 <= edges.length <= 200000.
  • 0 <= from, to, start < nodeCount.
  • Duplicate directed edges may appear.

More Google problems

See Google hiring insights
public int shortestCycleFromStart(int nodeCount, int[][] edges, int start) {
    // write your code here
}
nodeCount4
edges[[0,1],[1,2],[2,0],[1,3]]
start0
expected3
Checking account…