You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.

Return the length of the longest cycle in the graph. If no cycle exists, return -1.

A cycle is a path that starts and ends at the same node.

Input & Output

Example 1 — Graph with Cycle
$ Input: edges = [3,3,4,2,3]
Output: 3
💡 Note: The longest cycle is 3 → 2 → 4 → 3 with length 3. There's also a self-loop at node 1 (1 → 1) with length 1, but 3 is longer.
Example 2 — No Cycles
$ Input: edges = [2,-1,3,1]
Output: -1
💡 Note: Following paths: 0→2→3→1→(dead end), no cycles exist in this graph, so return -1.
Example 3 — Self Loop
$ Input: edges = [1,0,0]
Output: 2
💡 Note: There's a cycle 0 ↔ 1 with length 2. Node 2 points to node 0 but doesn't create a longer cycle.

Constraints

  • 1 ≤ edges.length ≤ 105
  • edges[i] == -1 or 0 ≤ edges[i] < edges.length
  • Each node has at most one outgoing edge

Visualization

Tap to expand
Longest Cycle in a Graph INPUT Directed Graph (edges array) 0 1 2 3 4 Cycle: 3 --> 2 --> 4 --> 3 edges[] array: 3 i=0 3 i=1 4 i=2 2 i=3 3 i=4 ALGORITHM STEPS 1 Initialize Timestamps Track visit time for each node visitTime[n] = -1 2 DFS from Each Node Start DFS from unvisited nodes for i in 0..n-1: dfs(i) 3 Detect Cycle If revisit node in same DFS, cycle found! Length = time diff 4 Track Max Cycle Update longest cycle length maxLen = max(maxLen, len) Time Stamps Example Node 3: time=0 Node 2: time=1 Node 4: time=2 Revisit 3! Len = 3-0 = 3 FINAL RESULT Longest Cycle Found: 3 2 4 3 --> 2 --> 4 --> 3 Output: 3 OK - Cycle length = 3 (nodes 3, 2, 4 form cycle) Key Insight: Using timestamps during DFS allows O(n) cycle detection. When we revisit a node with a timestamp from the SAME traversal (not a previous one), we found a cycle. The cycle length equals the difference between current time and the node's visit time. Each node is visited at most twice. TutorialsPoint - Longest Cycle in a Graph | Optimized DFS with Time Stamps Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
38.4K Views
Medium Frequency
~35 min Avg. Time
892 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