23. Topological Sort
Put things in the right order when order matters
You're writing a build system. Module A depends on module B, which depends on module C. You need to compile them in an order that respects every dependency — C first, then B, then A. But your project has hundreds of modules with a tangled web of dependencies. How do you find a valid build order?
This is topological sorting: given a directed acyclic graph (DAG), produce a linear ordering of its vertices such that for every directed edge u → v, vertex u comes before v in the ordering.
The Problem
Given a directed acyclic graph (DAG) with V vertices and E edges, produce a linear ordering of all vertices such that if there's an edge from u to v, then u appears before v in the ordering.
Why "acyclic"?
If the graph has a cycle (A → B → C → A), no valid ordering exists — A must come before B, B before C, and C before A, which is impossible. Topological sort only works on DAGs. If the algorithm detects a cycle, it reports that no valid ordering exists.
A DAG can have multiple valid topological orderings. For example, if A → C and B → C, both [A, B, C] and [B, A, C] are valid — A and B have no ordering constraint between them.
A Simple Example
A course prerequisite DAG
Algebra → Calculus → DiffEq
↓
Intro CS → Data Structures → Algorithms
↓
Databases
One valid order: Algebra, Intro CS, Calculus, Data Structures, DiffEq, Databases, Algorithms
Another valid order: Intro CS, Algebra, Calculus, Data Structures, Databases, DiffEq, Algorithms
There are two classic approaches: Kahn's algorithm (BFS-based) and DFS-based topological sort.
Kahn's Algorithm (BFS)
Kahn's algorithm (1962) works by repeatedly removing vertices with no incoming edges. The intuition: a vertex with no prerequisites can safely go first.
-
Compute in-degrees
For each vertex, count the number of incoming edges. Vertices with in-degree 0 have no dependencies.
-
Initialize a queue with all in-degree 0 vertices
These are the "roots" — they can go first in any order.
-
Process the queue
Dequeue a vertex, add it to the output. For each of its outgoing edges, decrement the in-degree of the target vertex. If a target's in-degree drops to 0, enqueue it.
-
Check for cycles
If the output contains all V vertices, we have a valid topological order. If not, the remaining vertices are part of a cycle.
Worked Example
Graph: A→C, A→D, B→D, C→E, D→E
A --→ C --→ E
| ↑
+--→ D ----+
↑
B ---+
Initial in-degrees: A:0 B:0 C:1 D:2 E:2
Queue: [A, B]
Step 1: Dequeue A. Output: [A]
A→C: in-degree[C] = 1→0, enqueue C
A→D: in-degree[D] = 2→1
Queue: [B, C]
Step 2: Dequeue B. Output: [A, B]
B→D: in-degree[D] = 1→0, enqueue D
Queue: [C, D]
Step 3: Dequeue C. Output: [A, B, C]
C→E: in-degree[E] = 2→1
Queue: [D]
Step 4: Dequeue D. Output: [A, B, C, D]
D→E: in-degree[E] = 1→0, enqueue E
Queue: [E]
Step 5: Dequeue E. Output: [A, B, C, D, E]
Queue: []
Result: A, B, C, D, E ✓ (all 5 vertices — no cycle)
Kahn's Pseudocode
function kahnTopSort(graph):
inDegree = {}
for each vertex v:
inDegree[v] = 0
for each edge (u, v):
inDegree[v] += 1
queue = all vertices where inDegree[v] == 0
result = []
while queue is not empty:
u = queue.dequeue()
result.append(u)
for each neighbor v of u:
inDegree[v] -= 1
if inDegree[v] == 0:
queue.enqueue(v)
if result.length != |vertices|:
error "Graph has a cycle!"
return result
DFS-Based Topological Sort
The DFS approach uses a clever observation: in a DFS on a DAG, a vertex finishes (all its descendants have been fully explored) before any of its ancestors finish. So if we record vertices in reverse finishing order, we get a valid topological sort.
-
Run DFS from each unvisited vertex
For each unvisited vertex, start a DFS. Track three states: unvisited, in-progress (on the current DFS path), and done.
-
Post-order recording
When a vertex finishes (all neighbors explored), prepend it to the result list. This naturally produces reverse-finishing order.
-
Cycle detection
If DFS encounters a vertex that's in-progress, we've found a back edge — the graph has a cycle and no topological order exists.
DFS Worked Example
Same graph: A→C, A→D, B→D, C→E, D→E
Start DFS from A:
Visit A (in-progress)
Visit C (in-progress)
Visit E (in-progress)
E has no unvisited neighbors. E done. Prepend E.
Result: [E]
C done. Prepend C.
Result: [C, E]
Visit D (in-progress)
D→E: E is done, skip.
D done. Prepend D.
Result: [D, C, E]
A done. Prepend A.
Result: [A, D, C, E]
Start DFS from B (still unvisited):
Visit B (in-progress)
B→D: D is done, skip.
B done. Prepend B.
Result: [B, A, D, C, E]
Final order: B, A, D, C, E ✓
Note that this is a different valid ordering than Kahn's produced — both are correct.
DFS Pseudocode
function dfsTopSort(graph):
state = {} // "unvisited", "in-progress", "done"
result = []
for each vertex v:
state[v] = "unvisited"
for each vertex v:
if state[v] == "unvisited":
dfs(v)
return result
function dfs(u):
state[u] = "in-progress"
for each neighbor v of u:
if state[v] == "in-progress":
error "Graph has a cycle!"
if state[v] == "unvisited":
dfs(v)
state[u] = "done"
result.prepend(u)
Kahn's vs. DFS
| Property | Kahn's (BFS) | DFS-based |
|---|---|---|
| Strategy | Remove vertices with no incoming edges | Reverse post-order of DFS |
| Cycle detection | Output has fewer than V vertices | Back edge to in-progress vertex |
| Complexity | O(V + E) | O(V + E) |
| Deterministic? | With a regular queue, no (depends on queue ordering) | No (depends on DFS start order) |
| Extra space | In-degree array + queue | State array + recursion stack |
| Yields unique "level" info? | Yes — BFS layers give the longest-path level | No |
Kahn's is generally easier to understand and implement iteratively. DFS-based is more natural if you're already doing a DFS traversal of the graph. Both run in O(V + E) time.
Complexity
Complexity
Time: O(V + E) — every vertex and every edge is processed
exactly once, whether using Kahn's BFS or DFS.
Space: O(V + E) — for the adjacency list, in-degree array
(or state array), and the output.
Where Topological Sort Is Used
| Application | How it uses topological sort |
|---|---|
| Build systems | make, Webpack, Gradle — compile modules in dependency order |
| Package managers | npm, pip, apt — install packages so dependencies are ready before dependents |
| Task scheduling | Order tasks so prerequisites complete first (project planning, CI pipelines) |
| Spreadsheet evaluation | Compute cells in dependency order so every cell's inputs are ready |
| Course planning | Determine a valid semester sequence respecting prerequisites |
| Data pipelines | Execute ETL stages in the right order (Airflow, dbt) |
| Git commits | Commits form a DAG — topological sort gives a valid linear history |
Key Takeaways
- Topological sort produces a linear ordering of a DAG's vertices where every edge points "forward" in the ordering
- It only works on directed acyclic graphs — cycles make a valid ordering impossible
- Kahn's algorithm repeatedly removes vertices with in-degree 0 (BFS-based)
- DFS-based sort records vertices in reverse finishing order
- Both run in O(V + E) time and detect cycles
- A DAG may have multiple valid topological orderings
- It's the backbone of build systems, package managers, and task schedulers
Try It Yourself — Topological Sort
Build a DAG by clicking to add nodes and dragging between nodes to create directed edges. Then watch Kahn's algorithm or DFS-based sort find a valid ordering. If you create a cycle, the algorithm will detect it and highlight the offending edges.
Topological Order
Topological sort turns the abstract structure of a DAG into a concrete, actionable sequence. It's one of those algorithms you encounter constantly once you start looking — every make build, every npm install, every spreadsheet recalculation relies on it. The connection to Git is direct: Git's commit graph is a DAG, and git log --topo-order is literally a topological sort. If you enjoyed the graph algorithms here, Dijkstra's and MSTs explore weighted graphs, while Union-Find tackles the closely related problem of tracking connected components.