Topological Sorting
Order tasks so every dependency comes before the task that needs it.
- waiting / queued
- active this step
- result
Count prerequisites
0 needs nothing, 1 and 2 need one course each, 3 needs two. Only 0 can start.
VARIABLES
- indegree
- [0, 1, 1, 2]
- queue
- [0]
- order
- []
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A topological order lists the nodes of a directed acyclic graph so every edge points forward. Kahn’s algorithm repeatedly takes a node with no remaining prerequisites.
Why it matters
Build systems, course schedules and pipelines all need a valid order - and need to detect when none exists because of a cycle.
Think of it like this
Getting dressed: socks before shoes, shirt before jacket - any order that respects those rules works.
Use it when
- Prerequisites or dependencies
- Detecting cycles in a directed graph
- DP over a directed acyclic graph
Avoid it when
- Undirected graphs
- Graphs with a cycle when you need a complete order - none exists
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Kahn’s algorithm | O(V + E) | O(V + E) |
| DFS-based ordering | O(V + E) | O(V + E) |
| Cycle check via order length | O(V + E) | - |
Often confused with: plain BFS - it explores distance; Kahn’s algorithm uses in-degrees on a directed graph.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- If the output has fewer than n nodes, there is a cycle
- Several valid orders can exist - ask whether any one is accepted
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Reversing the edge direction (pre to course vs course to pre)
- Forgetting nodes that have no edges at all
- Returning a partial order instead of reporting the cycle
Edge cases to test
- No prerequisites - any order works
- A cycle like [[0, 1], [1, 0]] - return []
- A course that depends on itself
Knowledge check
Quick check to lock in the intuition.
Kahn’s algorithm outputs only 3 of 4 nodes. What does that mean?
Practice
Apply what you just watched on real interview problems.