Find Eventual Safe States solution explained
Find Eventual Safe States gives you a directed graph and asks for every node from which all walks are guaranteed to stop at a node with no outgoing edges; return those safe nodes in increasing order. A node is unsafe exactly when it can reach a cycle. Either run a depth-first search that marks nodes as on-the-path or finished, or reverse the edges and peel nodes whose outgoing edges all lead to known safe nodes. Both run in O(V + E).
By Evin JohnPublished 9 min read
The problem, restated
You are given n nodes and, for each node, the list of nodes it has edges to. A node with no outgoing edges is a dead end. Call a node safe if every possible walk that starts there, choosing any edge at each step, eventually stops at a dead end. Return all safe nodes in increasing order. Edges can point back to the same node or create cycles of any length.
graph = [[1], [2, 3], [], [4], [1], [3, 6], [], [6]]
0 -> 1 4 -> 1
1 -> 2, 3 5 -> 3, 6
2 (dead end) 6 (dead end)
3 -> 4 7 -> 6
answer: [2, 6, 7]Nodes 2 and 6 are dead ends, so they are safe. Node 7 only leads to 6, so it is safe too. Nodes 1, 3 and 4 form a loop (1 to 3 to 4 to 1), so a walk can go around forever: unsafe. Node 0 leads into that loop, so it is unsafe. Node 5 is the interesting one: its edge to 6 is fine, but its edge to 3 enters the loop, and one bad option is enough to make it unsafe.
What the interviewer is checking
Underneath the wording, this is cycle detection in a directed graph with a twist: you must label every node, not just say whether a cycle exists. Interviewers look for the reframing (safe means cannot reach a cycle), a correct three-state depth-first search, and awareness that a recursive search can run out of stack on a long chain. Offering the reverse-graph peeling method shows you know how topological sorting relates to cycles.
Brute force: check each node's reachable set
For each node, collect every node reachable from it with a search. A node lies on a cycle exactly when it can reach itself. A node is safe if it is not on a cycle and nothing it can reach is on a cycle. This is correct and easy to argue, but it runs one search per node, O(V · (V + E)), and stores a reachable set for each.
def safe_nodes_brute(graph):
n = len(graph)
def reach(start): # nodes reachable using one or more edges
seen, stack = set(), list(graph[start])
while stack:
v = stack.pop()
if v not in seen:
seen.add(v)
stack.extend(graph[v])
return seen
reach_sets = [reach(v) for v in range(n)]
on_cycle = [v in reach_sets[v] for v in range(n)]
return [v for v in range(n)
if not on_cycle[v] and not any(on_cycle[u] for u in reach_sets[v])]Approach 1: three-color depth-first search
Give every node a color. White means not visited, grey means on the current search path, and black means finished. If the search follows an edge into a grey node, it has found a cycle, so the current node is unsafe. If it follows an edge into a finished node that is already known to be unsafe, the current node is unsafe as well. When a node finishes, its result is passed to its parent on the path. Each node and edge is handled once, so the whole search is O(V + E).
The version below uses an explicit stack of (node, next edge index) pairs instead of recursion. A chain of a few hundred thousand nodes would overflow Python's default recursion limit, and this form avoids that entirely.
WHITE, GREY, BLACK = 0, 1, 2
def safe_nodes(graph):
n = len(graph)
color = [WHITE] * n # GREY = on the current path, BLACK = finished
unsafe = [False] * n
for root in range(n):
if color[root] != WHITE:
continue
color[root] = GREY
stack = [(root, 0)] # (node, index of the next edge to try)
while stack:
node, i = stack[-1]
if i < len(graph[node]):
stack[-1] = (node, i + 1)
nxt = graph[node][i]
if color[nxt] == WHITE:
color[nxt] = GREY
stack.append((nxt, 0))
elif color[nxt] == GREY or unsafe[nxt]:
unsafe[node] = True # a cycle, or a road into one
else:
stack.pop()
color[node] = BLACK
if stack and unsafe[node]:
unsafe[stack[-1][0]] = True # pass the bad news up
return [v for v in range(n) if not unsafe[v]]Approach 2: peel from the dead ends
Turn the question around. A node is safe once every one of its outgoing edges is known to lead to a safe node. Dead ends qualify immediately. So reverse every edge, give each node a counter equal to its number of outgoing edges, and start a queue with the dead ends. Each time a node is confirmed safe, decrease the counter of every node that points to it; when a counter reaches zero, that node is safe too. Nodes that never reach zero can reach a cycle. This is Kahn's topological sort run from the sinks backward.
function eventualSafeNodes(graph) {
const n = graph.length;
const pointsHere = Array.from({ length: n }, () => []); // reversed edges
const outLeft = new Array(n).fill(0);
graph.forEach((targets, v) => {
outLeft[v] = targets.length;
for (const t of targets) pointsHere[t].push(v);
});
const queue = [];
for (let v = 0; v < n; v++) if (outLeft[v] === 0) queue.push(v); // dead ends are safe
const safe = new Array(n).fill(false);
for (let head = 0; head < queue.length; head++) {
const v = queue[head];
safe[v] = true;
for (const u of pointsHere[v]) {
outLeft[u]--;
if (outLeft[u] === 0) queue.push(u); // every road out of u is now known safe
}
}
const result = [];
for (let v = 0; v < n; v++) if (safe[v]) result.push(v);
return result;
}Peeling the example
The counters start at 1, 2, 0, 1, 1, 2, 0, 1 for nodes 0 to 7, so the queue begins with 2 and 6. Confirming 2 lowers node 1's counter to 1. Confirming 6 lowers node 5 to 1 and node 7 to 0, so 7 joins the queue. Confirming 7 changes nothing, because no edge points to 7. The queue is empty, and the safe nodes are 2, 6 and 7. Nodes 1 and 5 are left with one unconfirmed edge each, both leading into the loop.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Reachable set from every node | O(V · (V + E)) | O(V²) for the sets |
| Three-color depth-first search | O(V + E) | O(V) plus the explicit stack |
| Peeling on the reversed graph | O(V + E) | O(V + E) for the reversed edges |
Edge cases
- A self-loop (a node pointing to itself) is a cycle, so that node is unsafe.
- A graph with no edges: every node is a dead end and every node is safe.
- One big cycle through every node: nothing is safe, and the answer is empty.
- A very long chain: use the iterative search or peeling, since recursion can overflow.
- A node with one edge to a dead end and one edge into a loop: unsafe, because every walk must end.
Mistakes to avoid
- Using only two colors (visited or not), which cannot tell a cycle from a node finished earlier on another path.
- Marking a node safe because one of its edges leads to a dead end; all edges must.
- Running the peeling on the original edges instead of the reversed ones.
- Forgetting to propagate unsafe from a child that finished after the parent last checked it.
- Returning nodes in the order they were confirmed instead of sorted.
Follow-up questions
- Return the nodes on cycles only. Use strongly connected components: nodes in a component of size two or more, or with a self-loop.
- The graph changes over time. Removing an edge can only make nodes safer, and adding one can only make them less safe. The simplest correct answer is to recompute in O(V + E) after each batch of changes, and to say so before reaching for anything cleverer.
- Find one safe walk's length from each node. On the safe part the graph is acyclic, so a dynamic program over the peeling order gives the longest walk to a dead end.
- Which nodes can reach some dead end? That is a different question: search backward from dead ends without the counters.
How to explain it
Fictional example
- Candidate
- A node is unsafe exactly when some walk from it can loop forever, which means it can reach a cycle. So this is cycle detection, but I need an answer for every node.
- Candidate
- I'll do a depth-first search with three colors. Grey means on my current path, so an edge to grey is a cycle. When a child turns out unsafe, so does its parent. I'll keep the stack explicit so a long chain doesn't overflow.
- Candidate
- Another way is to reverse the edges and peel from the dead ends, like a topological sort. Both are linear.
Related walkthroughs
Minimum Number of Vertices to Reach All Nodes also reads a directed graph's structure through edge counts. Critical Connections in a Network uses depth-first search timing on an undirected graph, and Count Sub Islands decides pass or fail for whole components of a grid. All walkthroughs are on the coding problems hub.
Practicing cycle problems with Natively
Three-color searches are easiest to understand by tracing them by hand. During practice on Mac or Windows, Natively can read an adjacency list from a screenshot, follow the colors with you step by step, and suggest code for either method when you ask. It saves the session's transcript and notes, so afterward you can see whether you explained what grey means before you started coding. The AI interview assistant page covers the coding features.
Questions people ask
How do you solve Find Eventual Safe States?
A node is safe if it cannot reach a cycle. Use a three-color depth-first search that marks nodes on the current path, or reverse the edges and peel nodes whose outgoing edges all lead to known safe nodes, starting from dead ends.
Why does Find Eventual Safe States need three colors?
Grey marks nodes on the current path, so an edge into grey is a cycle. Black marks finished nodes whose result is already known. Two colors cannot tell these apart.
What is the time complexity of Find Eventual Safe States?
O(V + E) for both the depth-first search and the peeling method.
Is a node with one edge to a dead end and one into a cycle safe?
No. Every walk from a safe node must end at a dead end, so one edge into a cycle makes it unsafe.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
