Imagine you have a directed graph where each node can have at most one outgoing edge - like a one-way street system where each intersection has only one exit!

You're given n nodes numbered from 0 to n-1, represented by an array edges where edges[i] tells you which node you can reach from node i. If edges[i] = -1, it means node i has no outgoing edge (a dead end).

Your mission: Find the longest cycle in this graph! A cycle occurs when you can start at a node, follow the directed edges, and eventually return to your starting point.

Goal: Return the length of the longest cycle, or -1 if no cycle exists.

Example: If edges = [3,3,4,2,3], there's a cycle 3 → 2 → 4 → 3 with length 3.

Input & Output

example_1.py — Basic Cycle
$ Input: edges = [3,3,4,2,3]
Output: 3
💡 Note: The graph has nodes 0→3, 1→3, 2→4, 3→2, 4→3. Starting from node 3, we get the path 3→2→4→3, forming a cycle of length 3.
example_2.py — Multiple Cycles
$ Input: edges = [2,-1,3,1]
Output: 3
💡 Note: We have 0→2, 1→-1, 2→3, 3→1. The cycle is 1→3→1 (length 2) and 2→3→1→3 but since 1 doesn't connect back, the actual cycle is 1→3→1 (length 2). Wait, let me recalculate: 0→2→3→1→(dead end). Actually, there's no cycle here since 1→-1 is a dead end.
example_3.py — No Cycle
$ Input: edges = [1,2,-1]
Output: -1
💡 Note: The path is 0→1→2→(dead end). No cycles exist since node 2 has no outgoing edge (edges[2] = -1).

Constraints

  • n == edges.length
  • 2 ≤ n ≤ 105
  • -1 ≤ edges[i] < n
  • edges[i] ≠ i (no self-loops)
  • Each node has at most one outgoing edge

Visualization

Tap to expand
🔄 Treasure Hunt: Finding the Longest Loop🏰Castle (t=0)🏔️Mountain (t=1)🏝️Island (t=2)🌋Volcano (t=3)📜 Adventure Logt=0: Arrived at Castle 🏰t=1: Reached Mountain 🏔️t=2: Found Island 🏝️t=3: Discovered Volcano 🌋t=4: Back to Mountain! Loop detected: 4-1 = 3 steps
Understanding the Visualization
1
Start Journey
Begin at an unvisited location and mark the time you arrived
2
Follow Arrows
Keep following the arrows, marking your arrival time at each new location
3
Detect Loop
If you reach a location you've already visited in this journey, you've found a loop!
4
Measure Loop
Calculate loop length by subtracting your original arrival time from current time
Key Takeaway
🎯 Key Insight: By using timestamps instead of complex state tracking, we can detect cycles in a single pass. When we revisit a location with a timestamp, the cycle length is simply the difference between current time and the stored timestamp!
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
68.2K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen