A directed graph is given as adjacency lists. A vertex is safe if every path from it eventually stops at a vertex with no outgoing edges. Return all safe vertices in ascending order.
Before you code
A vertex is unsafe exactly when some path from it reaches a cycle. Three-color DFS discovers that: any vertex that is still gray when a cycle is found, or that leads to an unsafe vertex, is unsafe.
Hints
- White: unvisited. Gray: on the current path. Black: finished and safe.
- In DFS, if a neighbor is gray, or is unsafe, this vertex is unsafe: return false and leave it gray.
- A vertex whose neighbors all return safe turns black and is safe.
- Alternative: reverse the edges and run Kahn's algorithm from the terminal vertices.
Production & complexity notes
When solving Find eventual safe states on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Cycles and connected components to reinforce the underlying pattern.
What it practices
Directed cycle detection with colors, from Cycles and connected components.