Question presented to candidate: "What is a topological sort, and when would you use one? Walk me through an algorithm for it and code it in Python."
What a strong answer should cover:
- A topological order lists every node so that each edge u -> v has u before v; it exists only for a DAG (no cycles), and it is usually not unique.
- Kahn's algorithm: in-degrees, a queue of in-degree-0 nodes, decrement neighbours; fewer than n nodes placed means a cycle.
- The DFS alternative: reverse post-order, with three colours to catch a back edge.
- O(V + E) time and space for both, and real uses: build order, package installs, spreadsheets, course prerequisites, DP on a DAG.
- Python specifics:
collections.dequefor an O(1)popleft(notlist.pop(0)),heapq(a min-heap) for the smallest order, the 1000-frame default recursion limit for DFS, and the standard-librarygraphlib.TopologicalSorter.
Code / implementation expected: Yes โ a kahn(n, edges) function in Python that returns an order or signals a cycle.