Longest Cycle in a Graph

Hard

Topics
GraphDFS

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.

01342
Green cycle: 3 → 4 → 2 → 3 (length 3)

Example 1

3031422334
Input:  nums = [3,3,4,2,3]
Output: 3
Explanation: Nodes 2 → 4 → 3 → 2 form a cycle of length 3.

Example 2

20-113213
Input:  nums = [2,-1,3,1]
Output: -1
Explanation: No cycle exists.

Example 3

-1041-12230445
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

  1. For each unvisited node, start walking forward.
  2. Record the step number when you first visit each node in the current walk.
  3. If you hit a node you have already seen in this walk, the cycle length = current step - step when you first saw it.
  4. If you hit -1 or an already-processed node from a previous walk, stop — no cycle from this starting point.
  5. 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 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 best
SensAI
Beta
Tap the mic to stop voice mode