Find Eventual Safe States
Problem Statement
There are n nodes labelled from 0 to n − 1. graph[i] lists the nodes that node i has an arrow to.
A node is terminal if it has no arrows going out. A node is safe if every walk that starts there ends at a terminal node or at another safe node. In other words, no walk from a safe node can go round a loop forever.
Return all the safe nodes, sorted in ascending order.
graph, an adjacency list: graph[i] is the list of nodes that i points to.
The safe nodes, sorted in ascending order.
Nodes 5 and 6 have no arrows out, so they are terminal. Nodes 2 and 4 only point at 5, so they are safe. Nodes 0, 1 and 3 form the loop 0 → 1 → 3 → 0, so a walk from any of them can go round forever.
Only node 4 is terminal. Node 1 has an arrow to itself, and nodes 0, 2 and 3 can reach the loop 0 → 3 → 0, so none of them is safe.
- • 1 ≤ n ≤ 10^4
- • 0 ≤ graph[i].length ≤ n
- • 0 ≤ graph[i][j] ≤ n − 1
- • Each graph[i] is sorted in strictly increasing order.
- • The graph may contain self-loops.
- • The number of arrows is between 1 and 4 · 10^4.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each node, search everything it can reach and check whether the search runs into a loop
Count arrows out; start from terminal nodes; a node joins once all of its arrows lead to safe nodes
A node is unsafe exactly when a loop can be reached from it. For each node, run a search that follows arrows and keeps track of the nodes on the current path. If the search steps onto a node that is already on the path, a loop is reachable and the node is unsafe.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Topological Sort translate into production architectures and low-level memory mechanics.