TRT
Sign in
mediumAdvancedLeetCode#three-color DFS#cycle detection

Find eventual safe states

Find the vertices of a directed graph from which every path ends at a terminal vertex, using three-color DFS.

The Runtime Theory Team1 min read
Taught inCycles and connected componentsPro — members onlyOne walk over a graph can split it into connected pieces, tell whether it is a tree, and find cycles. Directed graphs need one extra idea: remembering which vertices are on the current path.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ingraph = [[1, 2], [2, 3], [5], [0], [5], [], []]

out[2, 4, 5, 6]

ingraph = [[1, 2, 3, 4], [1, 2], [3, 4], [0, 4], []]

out[4]

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

  1. White: unvisited. Gray: on the current path. Black: finished and safe.
  2. In DFS, if a neighbor is gray, or is unsafe, this vertex is unsafe: return false and leave it gray.
  3. A vertex whose neighbors all return safe turns black and is safe.
  4. 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.

Not started

Sign in to save your learning progress.

Sign in to save