Longest Cycle in a Graph solution explained
Longest Cycle in a Graph has a linear-time answer because each node has at most one outgoing edge: walk from every unvisited node, stamp each node with a global clock as you go, and when the walk hits a node stamped during the same walk, the cycle length is the current clock minus that node's stamp. Every node is stamped once, so the whole thing is O(n) time and O(n) space.
By Evin JohnPublished 8 min read
The problem in plain words
There are n nodes numbered from 0. You receive an array called next with n entries. If next[i] is a node number, there is a directed edge from i to that node. If it is -1, node i has no outgoing edge. Since each node has at most one outgoing edge, you can think of every node as holding a single arrow, or no arrow. A cycle is a route that leaves a node, follows arrows, and comes back to the same node. Return the number of nodes on the longest cycle, or -1 when the graph has no cycle at all.
| next | Answer | Why |
|---|---|---|
| [2, 0, 1, 4, 3, -1] | 3 | 0 goes to 2, 2 goes to 1, 1 goes back to 0. Nodes 3 and 4 form a second cycle of length 2. Node 5 has no arrow. |
| [1, 2, -1] | -1 | A straight chain that stops at node 2. |
| [1, 2, 3, 1] | 3 | Node 0 is a tail leading into the cycle 1, 2, 3. The tail is not part of the cycle. |
| [-1, -1] | -1 | No edges at all. |
| [3, 3, 0, 2] | 3 | Nodes 0, 3 and 2 form a cycle. Node 1 points into it from outside. |
Clarify two things before you start. First, can a node point to itself? Many versions of this problem rule it out, but if allowed, that is a cycle of length 1, and the code below handles it. Second, the graph can have several disconnected pieces, so a single walk from node 0 is never enough.
Why it is a good interview question
General cycle detection in a directed graph is a DFS with three colors, and finding the longest simple cycle in a general graph is a hard problem. This question removes the difficulty by limiting every node to one arrow. The interviewer wants to see whether you notice that restriction and use it. Candidates who reach for a full DFS often get tangled in recursion and back-edge bookkeeping. Candidates who say each component is a set of tails flowing into at most one loop usually finish quickly.
Slow approach: walk from every node separately
From each start node, follow arrows and record the step number at which each node was first seen on this walk. If you reach -1, there is no cycle on this route. If you reach a node already recorded on this walk, you have closed a loop, and its length is the current step minus the step where that node was recorded. Take the maximum over all starts. Each walk can be n steps long and there are n starts, so this is O(n²) time with O(n) memory per walk.
def longest_loop_slow(nxt):
best = -1
for start in range(len(nxt)):
step_of = {}
node, step = start, 0
while node != -1 and node not in step_of:
step_of[node] = step
step += 1
node = nxt[node]
if node != -1:
best = max(best, step - step_of[node])
return bestThe waste is obvious once you write it: a long tail feeding a cycle gets walked again from every node on the tail, and the cycle itself gets measured many times.
Main approach: one clock for all walks
Keep a single array stamp, with 0 meaning never visited, and a counter clock that starts at 1 and only goes up. For each node that is still unvisited, start a walk. Remember walk_start, the clock value when this walk began. At each node, if it is unvisited, give it the current clock value, advance the clock and follow its arrow. Stop when you hit -1 or a node that already has a stamp.
Now look at where you stopped. If the stamp of that node is at least walk_start, it was stamped during this very walk, so you have found a new cycle. Its length is clock minus that stamp, because the stamps on the cycle are consecutive. If the stamp is smaller than walk_start, the walk ran into territory an earlier walk already explored, and any cycle there was measured then. No node is stamped twice, so total work is O(n).
def longest_loop(nxt):
n = len(nxt)
stamp = [0] * n
clock = 1
best = -1
for start in range(n):
if stamp[start]:
continue
walk_start = clock
node = start
while node != -1 and stamp[node] == 0:
stamp[node] = clock
clock += 1
node = nxt[node]
if node != -1 and stamp[node] >= walk_start:
best = max(best, clock - stamp[node])
return bestfunction longestLoop(nxt) {
const n = nxt.length;
const stamp = new Int32Array(n);
let clock = 1;
let best = -1;
for (let start = 0; start < n; start++) {
if (stamp[start] !== 0) continue;
const walkStart = clock;
let node = start;
while (node !== -1 && stamp[node] === 0) {
stamp[node] = clock++;
node = nxt[node];
}
if (node !== -1 && stamp[node] >= walkStart) {
best = Math.max(best, clock - stamp[node]);
}
}
return best;
}A second linear method: peel off the tails
Count how many arrows point into each node. Put every node with no incoming arrows in a queue and remove it, which lowers the count of the node it points to. Repeat until the queue is empty, which is Kahn's topological sort. Whatever survives lies on a cycle, because only cycle nodes always keep an incoming arrow. Walk each surviving cycle once to measure it. This is also O(n) and is a nice follow-up answer if the interviewer asks for a different approach.
Tracing [1, 2, 3, 1]
- Start at node 0walk_start is 1. Stamp 0 with 1, 1 with 2, 2 with 3, 3 with 4. The clock is now 5.
- Follow the last arrowNode 3 points to node 1, which already has stamp 2.
- Same walk?Stamp 2 is at least walk_start 1, so this is a new cycle. Length = 5 - 2 = 3.
- Remaining startsNodes 1, 2 and 3 are already stamped and get skipped. The answer is 3.
Complexity
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Independent walk from every node | O(n²) | O(n) | Simple, too slow for large n |
| Shared timestamps | O(n) | O(n) | One pass, the usual expected answer |
| Kahn's algorithm, then measure | O(n) | O(n) | Good alternative; also lists cycle nodes |
| General DFS with colors | O(n) | O(n) plus recursion | Works but ignores the one-arrow structure |
Edge cases to test
- No edges at all: every entry is -1, the answer is -1.
- A single long chain: still -1, and the walk must stop cleanly at -1 without indexing next[-1], which Python would happily read as the last element.
- Several cycles of different sizes: the answer is the largest, not the first found.
- A tail that feeds into a cycle found by an earlier walk: the stamp check must reject it.
- Every node on one big cycle: the answer is n.
- A self-loop, if the input allows one: the answer should be at least 1.
Mistakes that cost points
- Using a plain visited boolean. Without the time of the visit, you cannot tell whether the node you hit belongs to this walk or an older one, and you either miss cycles or count tails as cycles.
- Counting the tail. In [1, 2, 3, 1], the walk visits 4 nodes, but the cycle has 3.
- Recursive DFS in Python on a chain of 100,000 nodes, which overflows the default recursion limit.
- Returning 0 instead of -1 when there is no cycle.
- Forgetting the outer loop over all start nodes, so pieces of the graph that node 0 cannot reach are never checked.
Explaining it in the room
Fictional example
- Candidate
- Each node has at most one arrow, so from any start there is exactly one route. It either ends at -1, joins something I already explored, or loops back on itself.
- Candidate
- I will stamp nodes with an increasing clock. When a walk stops on a stamped node, I compare that stamp with the clock value at the start of the walk. If it is newer, the loop is fresh and its length is the clock minus the stamp.
- Candidate
- No node is stamped twice, so it is linear. For [3, 3, 0, 2] the first walk stamps 0, 3, 2 and returns to 0, giving 3; the walk from 1 hits an older stamp and adds nothing.
Keep going with the batch
The Kahn's algorithm idea from this page drives Find All Possible Recipes, where peeling off ready items one at a time decides what can be built. For a grid version of the visited-marking habit, revisit Number of Enclaves. Graph traversal questions in general are collected on the algorithm interview questions page.
Using Natively in practice
While you drill graph problems, Natively can take a screenshot of the statement and outline a possible approach, which is most useful after you have committed to your own. It records a transcript of a practice session on your machine, so you can replay how you explained the timestamp check and spot where you rambled. Read about an AI assistant for coding interviews.
Questions people ask
How do you solve Longest Cycle in a Graph in linear time?
Walk from every unvisited node and stamp each node with an increasing clock. When a walk stops on a node stamped during the same walk, the cycle length is the clock minus that stamp. Each node is stamped once, so it runs in O(n).
Why is a visited boolean not enough?
A boolean cannot tell whether the node you reached was seen in the current walk or an earlier one. Storing the visit time and comparing it with the walk's start time separates a new cycle from a path into old territory.
Can I use topological sort for this problem?
Yes. Remove nodes with no incoming edges using Kahn's algorithm; every node left lies on a cycle. Then walk each remaining cycle once to measure it, which is also O(n).
What should the function return if there is no cycle?
Return -1. Returning 0 is a common slip that fails the case where every route ends at a node with no outgoing edge.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
