progress

~/problems / Graphs / Cycle detection

Find Eventual Safe States

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Implement eventual_safe_nodes(graph) -> list[int].

graph is a directed graph on nodes 0..n-1 given as adjacency lists: graph[i] lists the nodes that i has an edge to. Self-loops are allowed. A terminal node has no outgoing edges. A node is safe if every path that starts from it eventually reaches a terminal node, which means no path from it ever reaches a cycle. Return all safe nodes in increasing order.

eventual_safe_nodes([[1], [2], [0, 3], [], [4], [3]])
# [3, 5]
# 0 -> 1 -> 2 -> 0 is a cycle, so 0, 1 and 2 are unsafe. 3 is terminal.
# 4 has a self-loop, so it's unsafe. 5 only leads to 3, so it's safe.
A six-node directed graph: the cycle 0, 1, 2 and the self-looping node 4 are unsafe, while terminal node 3 and node 5, which only leads to 3, are safe.

n goes up to 10,000.

⭐ Bonus: a speed test with 10,000-node chains earns a star in O(n + m) (m edges) without deep recursion. A separate search from every node is O(n²) there.

Show hint

Work backwards from the terminal nodes: a node is safe exactly when all of its out-edges lead to nodes already known to be safe.

Topic: Cycle detection. Visited / on-stack sets; symlinks, CNAMEs, instruction loops.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc