What is topological sorting?
Why Interviewers Ask This
Mid-level Data Structures & Algorithms roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
Topological sort is a linear ordering of vertices in a DAG (Directed Acyclic Graph) such that for every directed edge u → v, vertex u comes before v in the ordering. Only applicable to DAGs (no cycles — a cycle would create a circular dependency with no valid ordering). Two algorithms: (1) Kahn's algorithm (BFS-based): compute in-degree of all nodes; add all zero in-degree nodes to queue; process: dequeue a node, add to result, decrement in-degree of neighbors, add newly zero in-degree nodes to queue; if result has fewer nodes than the graph, a cycle exists. Time: O(V+E); (2) DFS-based: run DFS; after visiting all neighbors of a node, push it to a stack; the stack reversed is the topological order. Time: O(V+E). Applications: (1) Build systems — determine compilation order (file A must compile before B if B depends on A); (2) Course prerequisite scheduling; (3) Task scheduling with dependencies; (4) Package manager dependency resolution (npm, pip); (5) Spreadsheet calculation order; (6) Pipeline stages. If a cycle is detected during topological sort, it indicates a circular dependency (error in build systems/course prerequisites).
Pro Tip
This topic has Data Structures & Algorithms-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.