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?
- A. Finish times are irrelevant; only visit (pre-order) times matter
- B. Topological sort via DFS only works on trees, not general DAGs
- C. DFS visits nodes in topological order directly, with no need to reverse anything
- 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
- Problem: A problem requires finding all pairs in an array that sum to a target, allowing duplicate pairs to be counted once. Which is the…
- Problem: Which statement about the time complexity of building a suffix array naively (sorting all n suffixes with standard string…
- Problem: A delivery app logs the parcel weights of a day in an array. Return the indices of the two parcels whose weights add up exactly…
- Problem: Given an unsorted array of n ≤ 10⁵ integers and a target, report whether two different positions hold values summing to the…
- Problem: A stock tracker gets daily prices and must report the best profit from one buy followed by one later sell (0 if no profit is…
- Problem: Find the largest sum of a non-empty contiguous block of an array (values may be negative). python def best(a): cur = ans = a[0]…