Find Eventual Safe States

medium

Given a directed graph with V vertices (0 .. V-1) and directed edges edges, a node is terminal if it has no outgoing edges, and safe if every path starting from it eventually reaches a terminal node (i.e. it can never get stuck in a cycle). Return all safe nodes in ascending order.

Hints

A node is safe if it can never reach a cycle — every path from it ends at a terminal node.
3-state DFS: a node is safe iff all its successors are safe; an on-path revisit means a cycle.
Or reverse the edges and run Kahn's from the terminal (out-degree 0) nodes.

Common doubts

Terminal nodes are trivially safe. In the reversed graph they're the sources, so Kahn's grows the safe set outward — a node is safe once all the nodes it pointed to are.
You must distinguish a node still on the current path (revisiting it = cycle = unsafe) from one already proven safe.
Yes — with no outgoing edges, the only 'path' from them is themselves, which trivially terminates.

Interview follow-ups

Unsafe nodes are exactly those that can reach a directed cycle; safe nodes are the rest.
The 3-state colouring already memoizes: once a node is marked safe/unsafe it isn't recomputed.

Fun facts

  • LeetCode 802 — a cycle-detection problem dressed up as 'eventual safety'.
  • The reverse-Kahn view makes safe nodes a backward-growing topological order.

Asked at

AmazonGoogle
Frequently Sometimes Occasionally
Example 1
Input: V = 4, edges = [[0,1],[1,2],[2,0],[2,3]]
Output: [3]
3 is terminal; 0,1,2 lie on a cycle.
Example 2
Input: V = 7, edges = [[0,1],[0,2],[1,2],[2,3],[2,4],[3,5],[4,5]]
Output: [0, 1, 2, 3, 4, 5, 6]
No cycles, so every node is safe.
Constraints

- 1 <= V <= 10^4 - 0 <= edges.length <= 4·10^4 - edges are directed u -> v - no duplicate edges

Solve this problem →