AlgoInsight

DSA problem

Find Eventual Safe States

MediumTopological SortPattern: Topological Sorttop300AmazonGoogleMetaMicrosoftBloomberg

You are given a directed graph with n nodes labeled 0 to n - 1 represented as an adjacency list graph, where graph[i] is the list of nodes reachable in one step from node i. A node is called terminal if it has no outgoing edges. A node is called safe if every possible path starting from that node eventually leads to a terminal node — equivalently, no path from it can revisit a node on the way (no path enters a cycle). Return all safe nodes in ascending order.

Phrased differently, a node is safe iff it is not part of any cycle and cannot reach any cycle. The standard topological-sort framing makes this trivial: reverse every edge of the graph. In the reversed graph, terminal nodes become the only nodes with out-degree zero in the original, which translates to in-degree zero in the reversed graph after the flip, so they are the natural Kahn's sources.

Run Kahn's BFS on the reversed graph. Whenever a node is popped from the queue, it is reachable only through chains of nodes that eventually end at a terminal — i.e. it is a safe node. Push each newly zero-in-degree node onto the queue and mark every popped node as safe. Nodes that remain with non-zero in-degree at the end live inside a cycle or feed into one and so are unsafe.

Finally, scan 0..n - 1 and emit the indices marked safe — they are already returned in ascending order. The whole algorithm runs in O(V + E) time and uses O(V + E) space, optimal for the size of the input graph.

Examples

Example 1
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: Nodes 5 and 6 are terminal. Node 2 only reaches 5; node 4 only reaches 5. Nodes 0, 1, 3 lie on the cycle 0 → 1 → 2 with backedge 3 → 0 or reach it, so they are unsafe.
Example 2
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation: Only node 4 is terminal and safe. Every other node can reach the cycle 0 → 1 → 1 (self-loop via 1 → 1 through 1 → 2 → 3 → 0) or similar, so they are unsafe.
Example 3
Input: graph = [[],[0,2,3,4],[3],[4],[]]
Output: [0,1,2,3,4]
Explanation: No cycles exist in this DAG, so every node eventually reaches a terminal and is safe.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

graphtopological-sortbfsreverse-graph

Browse all DSA problems