Topological sort
medium 20 minA topological sort lists the nodes of a directed graph so that every edge u → v has u before v: a valid order for tasks with prerequisites.
Chapter mnemonic
Kahn’s topological sort
Bake what is ready. Cross it off. Unlock the next recipe.
The ready queue is empty, and three recipes remain. What does that tell you?
The remaining dependencies contain a cycle. A full topological ordering is impossible.
Video lesson · Chapter 1 of 8
The bindery schedule
Topological sort in 75 seconds
1:19Reel
How it works
Step through the idea, or press Play.
Draw the dependencies. Each rule "u must come before v" is a directed edge u → v; the graph must have no cycle
Understand it
Start here
What topological sort is
You have tasks, and some must happen before others: CS101 before CS201, compile utils before main, underwear before pants. Draw each rule as a directed edge and a topological sort is a list of all the nodes in which every edge points forward, from earlier to later. It does not sort by value; it sorts by dependency.
Recap: directed graphs
Vertices, one-way edges, in-degree and out-degree, adjacency lists. All covered in Intro to graphs; this page builds on it.
DAG
A Directed Acyclic Graph: one-way edges and no way to follow arrows back to where you started.
Linear order
Every node exactly once, and for each edge , appears before .
Usually many answers
Five courses below have 5 valid orders out of arrangements. Any one of them is correct.
The course schedule used throughout this page
The precondition
Only DAGs have an order
If the arrows form a loop, there is no first node in it. Each course on the loop waits on the one before it, all the way round, so none of them can ever start. A topological order exists if and only if the directed graph has no cycle.
A cycle: who goes first?
Existence
Method 1
Kahn's algorithm: peel off the zeros
A node's in-degree is how many arrows point into it: how many prerequisites it still waits on. A node with in-degree is ready right now. Output one, delete its outgoing edges (decrement each successor's in-degree), and new zeros appear. Keep the ready nodes in a queue and repeat until it is empty. Remember it as ZERO.
- 1Zerofind every in-degree 0 node
- 2Enqueuethey are ready
- 3Removepop one, decrement successors
- 4Outputappend to the order
Loop until the queue is empty, then compare the output count with V.
Kahn's algorithm
from collections import dequedef kahn(n, adj): indeg = [0] * n for u in range(n): for v in adj[u]: indeg[v] += 1 queue = deque(u for u in range(n) if indeg[u] == 0) order = [] while queue: u = queue.popleft() order.append(u) for v in adj[u]: indeg[v] -= 1 if indeg[v] == 0: queue.append(v) return order if len(order) == n else [] # [] means a cycleadj = [[1, 3], [4], [3], [4], []]print(kahn(5, adj)) # [0, 2, 1, 3, 4]print(kahn(3, [[1], [2], [0]])) # [] (0 -> 1 -> 2 -> 0)Worked example
Kahn on the course schedule
| Pop | In-degree changes | Queue after | Order so far |
|---|---|---|---|
| start | CS101 0, CS102 1, Math 0, CS201 2, CS301 2 | CS101, Math | empty |
| CS101 | CS102 1 → 0, CS201 2 → 1 | Math, CS102 | CS101 |
| Math | CS201 1 → 0 | CS102, CS201 | CS101, Math |
| CS102 | CS301 2 → 1 | CS201 | CS101, Math, CS102 |
| CS201 | CS301 1 → 0 | CS301 | CS101, Math, CS102, CS201 |
| CS301 | none | empty | CS101, Math, CS102, CS201, CS301 |
The in-degrees add up to the edge count
Method 2
DFS: reverse the finish order
Run a depth-first search from every unvisited node and append a node to a list post only when it finishes, after all its successors are done. Whatever comes after a node finishes before it, so post lists the nodes back to front. Reverse it and you have a topological order.
DFS topological sort with three colours
def dfs_topo(n, adj): WHITE, GRAY, BLACK = 0, 1, 2 color = [WHITE] * n post = [] def dfs(u): color[u] = GRAY for v in adj[u]: if color[v] == GRAY: raise ValueError("cycle") if color[v] == WHITE: dfs(v) color[u] = BLACK post.append(u) # u finishes after all its successors for u in range(n): if color[u] == WHITE: dfs(u) return post[::-1]adj = [[1, 3], [4], [3], [4], []]print(dfs_topo(5, adj)) # [2, 0, 3, 1, 4]Worked example
DFS on the same courses
| Event | Path (GRAY) | post (finish order) |
|---|---|---|
| enter CS101, CS102, CS301 | CS101, CS102, CS301 | empty |
| CS301 has no edges: finish | CS101, CS102 | CS301 |
| CS102 done: finish | CS101 | CS301, CS102 |
| enter CS201; CS301 is BLACK, skip | CS101, CS201 | CS301, CS102 |
| CS201, then CS101 finish | empty | CS301, CS102, CS201, CS101 |
| enter Math; CS201 is BLACK; finish | empty | CS301, CS102, CS201, CS101, Math |
Kahn gave CS101, Math, CS102, CS201, CS301 and DFS gave Math, CS101, CS201, CS102, CS301. Both are correct. The full list of valid orders for this graph is: CS101, CS102, Math, CS201, CS301; CS101, Math, CS102, CS201, CS301; CS101, Math, CS201, CS102, CS301; Math, CS101, CS102, CS201, CS301; and Math, CS101, CS201, CS102, CS301. CS301 is always last because it is the only node everything leads to.
Cycles
Cycle detection with three colours
In a directed graph, "already visited" is not enough to call a cycle. A node finished on a different branch (BLACK) is harmless; only a node still on the current path (GRAY) closes a loop. So DFS keeps three states: WHITE not started, GRAY in progress, BLACK done. Kahn needs no colours at all: if the queue empties before all nodes are output, the leftovers sit on or behind a cycle.
A node's colour over time
| Edge u → v | Colour of v when seen | Meaning for topological sort |
|---|---|---|
| Tree edge | WHITE | Recurse into v |
| Back edge | GRAY | Cycle: v is an ancestor of u on the current path |
| Forward edge | BLACK (a descendant of u) | Harmless: v already finished |
| Cross edge | BLACK (another branch) | Harmless: like CS201 → CS301 above |
Proofs
Why both methods are correct
DFS: finish times run against the edges
post) therefore puts before for every edge.Proof. Look at the moment DFS examines edge ; is GRAY. If is WHITE, DFS enters and finishes it before returning to , so . If is BLACK, it already finished, so again . If were GRAY, would be an ancestor of and would be a cycle, which a DAG does not have. Every case gives .
Kahn: every DAG has a source
Proof of Kahn. Outputting a source and deleting its edges leaves a smaller graph that is still a DAG, so it has a source too; by induction Kahn outputs all nodes, and each node is output only after all its predecessors were output. Conversely, if Kahn stops early, every leftover node has in-degree at least 1 from other leftovers, so walking backwards among them must repeat a node: a cycle. That is exactly why the count check is a correct cycle test.
Complexity
Cost: O(V + E), and which method to use
Kahn's running time
| Aspect | Kahn's (BFS style) | DFS post-order |
|---|---|---|
| Core data | In-degree array + queue | Colour array + recursion stack |
| Cycle detection | Output count != V | Edge to a GRAY node (back edge) |
| Result order | Direct | Reversed finish order |
| Style | Iterative | Recursive (or explicit stack) |
| Easy extras | Levels / min rounds, smallest order with a heap | Finding the actual cycle, reachability |
| Watch out for | Using list.pop(0) as the queue | Python's recursion limit (about 1,000) |
Reach for Kahn when
- You need rounds, levels or the minimum number of semesters.
- You want a specific order, such as the lexicographically smallest.
- The graph may be deep: no recursion limit to worry about.
Reach for DFS when
- You need to report the cycle itself, not just that one exists.
- You are already running DFS for something else, such as reachability.
- Arrows mean "depends on" and post-order gives the answer directly.
Beyond the basics
Levels, smallest order, unique order, longest path
Levels (parallel rounds)
Process Kahn's queue one level at a time. The number of levels is the fewest rounds, which equals the number of nodes on the longest chain.
Smallest order
Swap the queue for a min-heap: always output the smallest ready node. .
Is the order unique?
Exactly when the queue never holds two nodes at once. Then consecutive nodes are joined by edges: a Hamiltonian path.
DP on a DAG
Process nodes in topological order and every predecessor is final before you need it: longest path, shortest path with negative weights, path counting.
The task pipeline in rounds
Longest path in a DAG in one pass
import heapqdef smallest_order(n, edges): adj, indeg = [[] for _ in range(n)], [0] * n for a, b in edges: adj[a].append(b) indeg[b] += 1 heap = [u for u in range(n) if indeg[u] == 0] heapq.heapify(heap) order = [] while heap: u = heapq.heappop(heap) # smallest ready node order.append(u) for v in adj[u]: indeg[v] -= 1 if indeg[v] == 0: heapq.heappush(heap, v) return order if len(order) == n else []def rounds(n, edges): adj, indeg = [[] for _ in range(n)], [0] * n for a, b in edges: adj[a].append(b) indeg[b] += 1 level, count, seen = [u for u in range(n) if indeg[u] == 0], 0, 0 while level: count, seen = count + 1, seen + len(level) nxt = [] for u in level: for v in adj[u]: indeg[v] -= 1 if indeg[v] == 0: nxt.append(v) level = nxt return count if seen == n else -1 # -1 means a cyclepipeline = [(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)]print(smallest_order(5, pipeline)) # [0, 1, 2, 3, 4]print(rounds(5, pipeline)) # 4Patterns
Course schedule, build order, alien dictionary
Course schedule
Pairs
[course, prereq]. "Can you finish?" is a cycle check; "give an order" is the sort itself. Mind the edge direction:prereq → course.Build order
Projects and dependencies. Compile in topological order; a cycle is the "circular dependency" error that
make, Gradle and Bazel report.Alien dictionary
Words sorted in an unknown alphabet. The first differing letter of each adjacent pair gives one edge; sort the letters.
Parallel courses
Minimum semesters when any number of courses can be taken at once: count Kahn's levels.
Alien dictionary: from sorted words to an alphabet
from collections import dequedef alien_order(words): adj = {c: set() for w in words for c in w} indeg = {c: 0 for c in adj} for a, b in zip(words, words[1:]): for x, y in zip(a, b): if x != y: if y not in adj[x]: adj[x].add(y) indeg[y] += 1 break else: if len(a) > len(b): return "" # "abc" listed before "ab" queue = deque(c for c in indeg if indeg[c] == 0) out = [] while queue: c = queue.popleft() out.append(c) for d in adj[c]: indeg[d] -= 1 if indeg[d] == 0: queue.append(d) return "".join(out) if len(out) == len(indeg) else ""print(alien_order(["wrt", "wrf", "er", "ett", "rftt"])) # wertfprint(alien_order(["z", "x", "z"])) # "" (cycle)| Problem | Difficulty | Technique |
|---|---|---|
| [Course Schedule](https://leetcode.com/problems/course-schedule/) (207) | Medium | Cycle check: Kahn count or three colours |
| [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) (210) | Medium | Return Kahn's order |
| [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) (269) | Hard | Edges from adjacent words, then Kahn |
| [Parallel Courses](https://leetcode.com/problems/parallel-courses/) (1136) | Medium | Count Kahn's levels |
| [Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) (802) | Medium | Kahn on the reversed graph, or three colours |
| [Build a Matrix With Conditions](https://leetcode.com/problems/build-a-matrix-with-conditions/) (2392) | Hard | Two independent topological sorts (rows, columns) |
Recap
Key takeaways
Key points
- A topological order lists every node so that each edge u → v has u before v. It exists exactly when the graph is a DAG.
- Kahn: count in-degrees, queue the zeros, pop and decrement successors, enqueue new zeros. Fewer than V outputs means a cycle.
- DFS: append each node when it finishes, then reverse. An edge to a GRAY node is a back edge and means a cycle.
- Three colours are needed in directed graphs: BLACK neighbours (finished elsewhere) are not cycles.
- Both run in O(V + E) time with O(V) extra space.
- Orders are rarely unique; check an answer with pos[u] < pos[v] for every edge.
- Levels of Kahn give the fewest parallel rounds; a min-heap gives the smallest order; DP in topological order solves longest paths.
- Get the edge direction right first: "a must come before b" is a → b.