Find Eventual Safe States
Given a directed graph as an adjacency list, a node is 'terminal' if it has no outgoing edges and 'safe' if every possible path starting from it eventually reaches a terminal node (equivalently, no path from it can ever enter a cycle). Return all safe nodes in ascending order.
Open official problem prompt ↗Identify every node from which you cannot possibly wander into an infinite loop — all walks terminate at a dead-end node.
Imagine one-way streets. A junction is 'safe' if no matter which turns you take you always end at a cul-de-sac. If any route from it can trap you circling a roundabout forever, it is unsafe.
- Input
- graph = [[1,2],[2,3],[5],[0],[5],[],[]]
- Output
- [2,4,5,6]
- Why
- Nodes 5 and 6 are terminal; 2 only leads to 5 and 4 only leads to 5, so all their paths terminate. Nodes 0,1,3 sit on the cycle 0->1->3->0, so they are unsafe.
n == graph.length1 <= n <= 10^40 <= graph[i].length <= n0 <= graph[i][j] <= n - 1graph[i] is sorted and has no duplicate valuesThe graph may contain self-loops and cycles