"You can't put on your shoes before your socks. Topological sort is the algorithm that, given a tangle of 'X must come before Y' rules, hands you a valid order to do everything — or tells you the rules contradict themselves."
The Problem
Given a directed acyclic graph (DAG) where an edge X→Y means "X must come before Y," a topological sort produces a linear ordering of all nodes such that every node appears after all its prerequisites. This is the math behind a thousand everyday systems: build tools compiling files in dependency order, package managers installing dependencies first, course prerequisites, task schedulers, spreadsheet cells recalculating in the right order, even the order Python imports your modules. Whenever the question is "what's a valid order to do these interdependent things?", it's topological sort.
Kahn's Algorithm: Peel Off the Ready Ones
The most intuitive method works by in-degree — how many prerequisites each node still has unmet. Repeatedly: take any node with zero remaining prerequisites (it's ready to go), output it, and remove its outgoing edges (decrementing its neighbors' in-degrees, possibly making them ready too). Use a queue to hold the ready nodes. Keep going until everything's output. It's BFS-flavored: process the frontier of currently-doable tasks, which unlocks the next frontier. O(V + E).
The alternative is DFS post-order: DFS the graph, and as each node finishes (all its descendants done), prepend it to the answer. Reverse the post-order and you have a valid topological order. Both are standard; Kahn's is often easier to reason about because 'zero prerequisites = ready' maps so cleanly to intuition.
The Bonus: Cycle Detection
Topological sort only works on a DAG — a graph with no cycles. And it tells you when that's violated: in Kahn's algorithm, if you run out of zero-in-degree nodes before outputting them all, the leftover nodes form a cycle (a mutual dependency: A needs B, B needs A — neither can ever be 'ready'). That's a real, useful diagnostic: a build system reporting "circular dependency detected" is a failed topological sort. So the algorithm doesn't just order the doable — it proves whether a valid order exists at all.