Topological Sort
Some tasks must happen before others: you install the foundation before the walls, compile a library before the program that uses it, take Programming 1 before Programming 2. Draw each task as a vertex and each "must come before" rule as a directed edge, and you get a directed acyclic graph (DAG). A topological order lists the vertices so that every edge points forward: each task comes after all of its prerequisites.
A topological order exists exactly when the graph has no cycle (you can't schedule "A before B before A"). A DAG usually has several valid orders.
Our example: a study plan
| Course | Requires |
|---|---|
| Intro (I) | — |
| Math (M) | — |
| Programming (P) | Intro |
| Data Structures (D) | Programming, Math |
| Web (W) | Programming |
| Algorithms (A) | Data Structures |
| Capstone (C) | Algorithms, Web |
Kahn's algorithm
Kahn's algorithm (1962) repeatedly takes a vertex with no remaining incoming edges ("all prerequisites done"):
- Count the incoming edges (in-degree) of every vertex. Vertices with in-degree 0 are ready.
- Take a ready vertex, append it to the order, and remove its outgoing edges: each neighbour's in-degree drops by one, and any neighbour that reaches 0 becomes ready.
- Repeat until no vertex is ready. If some vertices were never output, the graph has a cycle.
When several vertices are ready, this animation (and our code) takes them in alphabetical order:
def kahn(nodes, edges):
indegree = {v: 0 for v in nodes}
out = {v: [] for v in nodes}
for u, v in edges:
out[u].append(v)
indegree[v] += 1
ready = sorted(v for v in nodes if indegree[v] == 0)
print("ready at start:", ready)
order = []
while ready:
u = ready.pop(0) # alphabetically first ready vertex
order.append(u)
for v in sorted(out[u]):
indegree[v] -= 1
if indegree[v] == 0:
ready.append(v)
ready.sort()
print(f"output {u}, ready now {ready}")
if len(order) != len(nodes):
raise ValueError("cycle: no topological order exists")
return order
nodes = ["I", "M", "P", "D", "W", "A", "C"]
edges = [("I", "P"), ("P", "D"), ("M", "D"), ("P", "W"), ("D", "A"), ("A", "C"), ("W", "C")]
print("order:", " -> ".join(kahn(nodes, edges)))ready at start: ['I', 'M']
output I, ready now ['M', 'P']
output M, ready now ['P']
output P, ready now ['D', 'W']
output D, ready now ['A', 'W']
output A, ready now ['W']
output W, ready now ['C']
output C, ready now []
order: I -> M -> P -> D -> A -> W -> C
The order matches the animation's final frame. Each vertex and each edge is handled once, so Kahn's algorithm runs in O(V + E) (plus the sorting we added for a deterministic order).
DFS-based topological sort
A depth-first search gives another algorithm: when a vertex finishes (all its descendants are explored), every vertex it points to has already finished. So the reverse of the finishing order is a topological order.
graph = {"I": ["P"], "M": ["D"], "P": ["D", "W"], "D": ["A"], "W": ["C"], "A": ["C"], "C": []}
def topo_dfs(graph):
visited, finished = set(), []
def dfs(u):
visited.add(u)
for v in graph[u]:
if v not in visited:
dfs(v)
finished.append(u) # u is done after all its successors
for u in sorted(graph):
if u not in visited:
dfs(u)
print("finishing order:", finished)
return finished[::-1]
print("topological order:", " -> ".join(topo_dfs(graph)))finishing order: ['C', 'A', 'D', 'W', 'P', 'I', 'M']
topological order: M -> I -> P -> W -> D -> A -> C
A different order than Kahn's, but just as valid: check that every edge points forward.
def is_topological(order, edges):
position = {v: i for i, v in enumerate(order)}
return all(position[u] < position[v] for u, v in edges)
edges = [("I", "P"), ("P", "D"), ("M", "D"), ("P", "W"), ("D", "A"), ("A", "C"), ("W", "C")]
print(is_topological(["I", "M", "P", "D", "A", "W", "C"], edges))
print(is_topological(["M", "I", "P", "W", "D", "A", "C"], edges))
print(is_topological(["I", "P", "W", "C", "M", "D", "A"], edges)) # C before A: invalidTrue
True
False
Scheduling in parallel: levels
If several tasks can run at the same time, group them into levels: everything that is ready together forms one level. The number of levels is the minimum number of "semesters" (or build rounds) needed:
nodes = ["I", "M", "P", "D", "W", "A", "C"]
edges = [("I", "P"), ("P", "D"), ("M", "D"), ("P", "W"), ("D", "A"), ("A", "C"), ("W", "C")]
indegree = {v: 0 for v in nodes}
for _, v in edges:
indegree[v] += 1
level = sorted(v for v in nodes if indegree[v] == 0)
semester = 1
while level:
print(f"semester {semester}: {level}")
nxt = []
for u in level:
for a, b in edges:
if a == u:
indegree[b] -= 1
if indegree[b] == 0:
nxt.append(b)
level, semester = sorted(nxt), semester + 1semester 1: ['I', 'M']
semester 2: ['P']
semester 3: ['D', 'W']
semester 4: ['A']
semester 5: ['C']
Where topological sorting is used
- Build systems (Make, Gradle, bundlers): compile dependencies first.
- Package managers: install packages after their dependencies.
- Spreadsheets: recalculate cells after the cells they refer to.
- Task schedulers and CI pipelines: run jobs in dependency order, in parallel by level.
- Shortest paths in DAGs: relax edges in topological order for an
O(V + E)algorithm, even with negative weights.
Test yourself
When does a directed graph have a topological order?
- Always
- Exactly when it has no cycles
- Only when it is a tree
- Only when it is connected
In Kahn's algorithm, which vertices are ready to be output?
- Those with no outgoing edges
- Those with in-degree 0 (no remaining prerequisites)
- The vertex with the most edges
- Any vertex
In the DFS-based method, how is the topological order obtained?
- The order vertices are first visited
- The reverse of the order in which vertices finish
- Alphabetical order
- BFS order