Longest Cycle in a Graph
Hard
Topics
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 by a 0-indexed array nums of size n, where nums[i] indicates that there is a directed edge from node i to node nums[i]. If there is no outgoing edge from node i, then nums[i] == -1.
Return the length of the longest cycle in the graph. If no cycle exists, return -1.
Example 1
Input: nums = [3,3,4,2,3] Output: 3 Explanation: Nodes 2 → 4 → 3 → 2 form a cycle of length 3.
Example 2
Input: nums = [2,-1,3,1] Output: -1 Explanation: No cycle exists.
Example 3
Input: nums = [-1,4,-1,2,0,4] Output: -1
Constraints
- n == nums.length
- 1 <= n <= 10^5
- -1 <= nums[i] < n
- nums[i] != i (no self-loops)
Editorial — intuition, approach, complexity and pitfalls
Intuition
Since each node has at most one outgoing edge, this is a "functional graph." Following edges from any node is like walking along a single path — you either reach a dead end (-1) or loop back to a node you already visited. If you loop back, you found a cycle, and its length is how many steps it took to revisit that node.
Approach
- For each unvisited node, start walking forward.
- Record the step number when you first visit each node in the current walk.
- If you hit a node you have already seen in this walk, the cycle length = current step - step when you first saw it.
- If you hit -1 or an already-processed node from a previous walk, stop — no cycle from this starting point.
- Mark all nodes in the current walk as processed so you never re-walk them.
Dry Run
nums = [3, 3, 4, 2, 3] -- node i points at nums[i], or nowhere if -1
Each walk records the STEP at which it first met each node, so a repeat gives
the cycle length by subtraction rather than by re-walking it.
start at 0 path={} node 0, step 0
path={0:0} node 3, step 1
path={0:0,3:1} node 2, step 2
path={...,2:2} node 4, step 3
path={...,4:3} node 3, step 4 -- 3 is already in path
cycle length = 4 - path[3] = 4 - 1 = 3 ans 3
mark 0, 3, 2, 4 visited
start at 1 node 1, step 0 -> node 3, which is already visited, so stop
nothing new; mark 1 visited
2, 3, 4 are all visited, so the loop skips them.
answer 3 (the cycle 3 -> 2 -> 4 -> 3)
Two separate marks are doing two jobs. `path` is per-walk and gives the step
numbers that make the subtraction work. `visited` is global and is what stops
the next walk re-traversing ground already covered -- without it the whole thing
is O(n^2) rather than O(n), since every node would re-walk its own tail.Complexity
- Time — O(n): each node is visited at most once across all walks.
- Space — O(n): visited array + path tracking per walk.
Common Pitfalls
- Don't confuse "visited in this walk" with "visited in a previous walk" — only the first detects a cycle.
- Self-loops are excluded by constraints (nums[i] != i), so you don't need to handle them.
Full Solution — all languages
class Solution:
def longestCycle(self, nums):
n = len(nums)
visited = [False] * n
ans = -1
for i in range(n):
if visited[i]:
continue
path = {} # node -> step when first seen in this walk
node, step = i, 0
while node != -1 and not visited[node]:
if node in path:
# Found a cycle: length = steps since we first saw this node
ans = max(ans, step - path[node])
break
path[node] = step
step += 1
node = nums[node]
# Mark all nodes in this walk as fully processed
for key in path:
visited[key] = True
return ansimport java.util.*;
class Solution {
public int longestCycle(int[] nums) {
int n = nums.length;
boolean[] visited = new boolean[n];
int ans = -1;
for (int i = 0; i < n; i++) {
if (visited[i]) continue;
Map<Integer, Integer> path = new HashMap<>();
int node = i, step = 0;
while (node != -1 && !visited[node]) {
if (path.containsKey(node)) {
ans = Math.max(ans, step - path.get(node));
break;
}
path.put(node, step);
step++;
node = nums[node];
}
for (int key : path.keySet()) visited[key] = true;
}
return ans;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestCycle(vector<int>& nums) {
int n = nums.size(), ans = -1;
vector<bool> visited(n, false);
for (int i = 0; i < n; i++) {
if (visited[i]) continue;
unordered_map<int,int> path;
int node = i, step = 0;
while (node != -1 && !visited[node]) {
if (path.count(node)) {
ans = max(ans, step - path[node]);
break;
}
path[node] = step;
step++;
node = nums[node];
}
for (auto& [k, v] : path) visited[k] = true;
}
return ans;
}
};/**
* @param {number[]} nums
* @return {number}
*/
var longestCycle = function(nums) {
const n = nums.length;
const visited = new Array(n).fill(false);
let ans = -1;
for (let i = 0; i < n; i++) {
if (visited[i]) continue;
const path = new Map(); // node -> step
let node = i, step = 0;
while (node !== -1 && !visited[node]) {
if (path.has(node)) {
ans = Math.max(ans, step - path.get(node));
break;
}
path.set(node, step);
step++;
node = nums[node];
}
for (const key of path.keys()) visited[key] = true;
}
return ans;
};Full Solution — all languages
class Solution:
def longestCycle(self, nums):
n = len(nums)
visited = [0] * n
step = [0] * n
best = -1
clock = 1
for start in range(n):
if visited[start]:
continue
node = start
begin = clock
while node != -1 and not visited[node]:
visited[node] = 1
step[node] = clock
clock += 1
node = nums[node]
if node != -1 and step[node] >= begin:
best = max(best, clock - step[node])
return bestimport java.util.*;
class Solution {
public int longestCycle(int[] nums) {
int n = nums.length;
int[] visited = new int[n];
int[] step = new int[n];
int best = -1, clock = 1;
for (int start = 0; start < n; start++) {
if (visited[start] != 0) continue;
int node = start, begin = clock;
while (node != -1 && visited[node] == 0) {
visited[node] = 1;
step[node] = clock;
clock++;
node = nums[node];
}
if (node != -1 && step[node] >= begin) best = Math.max(best, clock - step[node]);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestCycle(vector<int>& nums) {
int n = nums.size();
vector<int> visited(n, 0), step(n, 0);
int best = -1, clock_ = 1;
for (int start = 0; start < n; start++) {
if (visited[start]) continue;
int node = start, begin = clock_;
while (node != -1 && !visited[node]) {
visited[node] = 1;
step[node] = clock_;
clock_++;
node = nums[node];
}
if (node != -1 && step[node] >= begin) best = max(best, clock_ - step[node]);
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var longestCycle = function(nums) {
const n = nums.length;
const visited = new Array(n).fill(0);
const step = new Array(n).fill(0);
let best = -1, clock = 1;
for (let start = 0; start < n; start++) {
if (visited[start]) continue;
let node = start;
const begin = clock;
while (node !== -1 && !visited[node]) {
visited[node] = 1;
step[node] = clock;
clock++;
node = nums[node];
}
if (node !== -1 && step[node] >= begin) best = Math.max(best, clock - step[node]);
}
return best;
};