synopsis · Trees & graphs · chapter 29
Topological Sort
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A topological order lists every vertex so all arrows point forward. It exists exactly when the directed graph has no cycle (a DAG).
- use it when
"Prerequisites", "depends on", "build order", "is it possible to finish?" — or an order hidden in sorted examples (alien dictionary).
- template
Kahn: count in-degrees → queue every 0 → poll, output, decrement neighbours, queue new 0s. Output count < V ⇒ cycle.
- cost
Kahn and DFS: O(V + E) time and space. Smallest order with a
PriorityQueue: O(V log V + E). Longest path on a DAG: O(V + E). - trap
[course, pre]means the arrow goes pre → course. Draw one edge on paper before you code. - trap
Directed cycle check needs three colours. A plain
visited[]calls a harmless diamond a cycle. - trap
DFS gives the finish order reversed — pop the stack. Kahn's order is already correct; don't reverse it.
- pro tip
Default to Kahn in Java: no recursion depth limit, a one-line cycle check, and it upgrades to min-heap order and DP.
- pro tip
Process vertices in topological order and DP gets easy: critical path, earliest finish, counting paths.
Shaky on a card? Open the chapter or flip its recall cards.