Skip to content
Problem 802 · LeetCode 802(opens in a new tab)

Find Eventual Safe States

MediumGraphs

You are given a directed graph with nodes numbered 0 to n − 1. graph[i] lists the nodes that node i has an edge to. A node with no outgoing edges is a terminal node.

Call a node safe if every walk that starts there, whatever edges it follows, is forced to stop at a terminal node. In other words, no walk from it can go on forever. Return all safe nodes in increasing order.

Example 1

Input:  graph = [[1], [2], [], [0, 4], [3], [2, 4]]
Output: [0, 1, 2]
Why:    0 → 1 → 2 must stop; 3 and 4 form a loop, 5 can enter it
2 more examples and the constraints

Example 2

Input:  graph = [[0], [0, 2], []]
Output: [2]
Why:    node 0 loops on itself and node 1 can step into 0

Example 3

Input:  graph = [[1, 2], [2], []]
Output: [0, 1, 2]
Why:    there is no loop at all

Constraints

  • 1 ≤ n ≤ 10,000
  • 0 ≤ total number of edges ≤ 40,000
  • Each graph[i] is sorted and has no repeats; self-loops may appear

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DFS with three coloursO(n + e)
  2. Peel terminals on the reversed graphO(n + e)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodes and 40,000 edgesVerdict
DFS with three coloursO(n + e)
Short; watch the recursion depth
Peel terminals on the reversed graphO(n + e)
Best; no recursion at all

n = number of nodes, e = number of edges. Both touch each node and edge a constant number of times.

Edge cases to test

  • Self-loop. A node listing itself, like [[0]], is never safe.
  • No loops at all. Every node is safe: the answer is 0 to n − 1.
  • Every node on a loop. The answer is an empty list.
  • One edge into a loop. A node is unsafe even if all its other edges lead to terminals.
  • Single terminal node. [[]] gives [0].

Common mistakes

  • Calling a node safe if some path reaches a terminal; it must be every path.
  • Resetting a node from 1 back to 0 after a failed search, which repeats work and can loop forever.
  • Counting in-degrees of the original graph instead of out-degrees, which peels from the wrong end.

How to talk through it

  1. 1Clarify. Can there be self-loops? Must every path end, or just one? Is the output sorted?
  2. 2Restate the condition. A node is unsafe exactly when it can reach a cycle.
  3. 3Pick a method. DFS with three colours detects cycles; peeling out-degree 0 nodes on reversed edges avoids recursion.
  4. 4Code the peel. Reverse edges, queue terminals, lower counts of predecessors, queue at 0.
  5. 5Test out loud. Run a self-loop and a node with one edge into a loop.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?