Longest Cycle in a Graph - Problem
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
Understanding the Visualization
1
Input Graph
Directed graph represented as edges array
2
DFS Traversal
Use DFS to detect cycles with timestamps
3
Output Result
Return length of longest cycle found
Key Takeaway
🎯 Key Insight: Since each node has at most one outgoing edge, we can use DFS with timestamps to detect cycles in a single pass with O(n) time complexity.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code