Data Structures & AlgorithmsVery hardICPC regional · Product Company SDE

Problem: Which best describes why DFS-based topological sort (using finish times, pushing to a stack) correctly produces a topological order for a DAG?

  1. A. Finish times are irrelevant; only visit (pre-order) times matter
  2. B. Topological sort via DFS only works on trees, not general DAGs
  3. C. DFS visits nodes in topological order directly, with no need to reverse anything
  4. D. A node finishes (post-order) only after all its descendants have finished, so reversing the finish-time order ensures every edge u->v has u appearing before v

Correct answer: D. A node finishes (post-order) only after all its descendants have finished, so reversing the finish-time order ensures every edge u->v has u appearing before v

Because DFS fully explores a node's descendants before marking it finished, any edge u->v means v finishes before u; sorting nodes by decreasing finish time (equivalently, pushing to a stack and reading it off) yields a valid topological order.

More Coding Interview Problems questions

Exams that ask this topic