FastPrepShortest Directed Cycle Through a Start Node
Problems/Shortest Directed Cycle Through a Start Node

Shortest Directed Cycle Through a Start Node

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source directly provides a directed graph, a specified node, the shortest return-to-self cycle objective, BFS, parent-path discussion, an edge illustration, and self-loop handling. Integer node encoding, returning cycle length instead of the path, the -1 sentinel, examples, and bounds are practice scaffolding. The judged core matches the visible source at about 91%.

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

  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
  • 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
All Google interview questionsSee Google hiring insights
Saved
public int shortestCycleFromStart(int nodeCount, int[][] edges, int start) {
    // write your code here
}
Checking account…