Topological Sort Pattern
Order things with dependencies — course schedules, build orders, alien dictionaries — with Kahn's in-degree BFS.
Whenever items have "must come before" relationships, you have a directed graph, and a valid ordering is a topological sort. If the dependencies contain a cycle, no valid order exists — detecting that is often the actual question. (Theory and the DFS approach: Topological sort & SCC.)
Prerequisites: 0 before 1 and 2; both before 3. Orders: 0,1,2,3 or 0,2,1,3.
When to use this pattern
- Tasks / courses / packages with prerequisites or dependencies.
- "Is it possible to finish all…?" (cycle detection) or "return an order".
- Deriving an ordering from pairwise comparisons (alien dictionary, sequence reconstruction).
- Processing in "rounds" where each round handles everything currently unblocked (parallel courses → number of semesters).
Template: Kahn's algorithm
- Build the adjacency list and the in-degree of every node.
- Queue every node with in-degree 0 (no prerequisites).
- Pop a node, append it to the order, and decrement its neighbours' in-degrees; queue any that reach 0.
- If the order contains every node, it's valid; otherwise there's a cycle.
Course Schedule II
int[] findOrder(int n, int[][] prereq) { // prereq {a, b}: take b before a
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] indeg = new int[n];
for (int[] p : prereq) { adj.get(p[1]).add(p[0]); indeg[p[0]]++; }
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i);
int[] order = new int[n];
int k = 0;
while (!q.isEmpty()) {
int u = q.poll();
order[k++] = u;
for (int v : adj.get(u)) if (--indeg[v] == 0) q.offer(v);
}
return k == n ? order : new int[0]; // cycle → impossible
}from collections import deque
def find_order(n, prereq):
adj = [[] for _ in range(n)]
indeg = [0] * n
for a, b in prereq: # take b before a
adj[b].append(a)
indeg[a] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order if len(order) == n else []function findOrder(n: number, prereq: [number, number][]): number[] {
const adj: number[][] = Array.from({ length: n }, () => []);
const indeg = new Array(n).fill(0);
for (const [a, b] of prereq) { adj[b].push(a); indeg[a]++; }
const order: number[] = [];
for (let i = 0; i < n; i++) if (indeg[i] === 0) order.push(i);
for (let h = 0; h < order.length; h++)
for (const v of adj[order[h]]) if (--indeg[v] === 0) order.push(v);
return order.length === n ? order : [];
}Variations
| Problem | Twist |
|---|---|
| Course Schedule I | Only return whether k == n |
| Parallel Courses (min semesters) | Process the queue level by level; count levels |
| Alien Dictionary | Build edges from the first differing letter of adjacent words |
| Smallest lexicographic order | Use a min-heap instead of a queue |
| Unique order? (Sequence Reconstruction) | The queue must never hold more than one node |
| Minimum height trees | Peel leaves (degree 1) layer by layer from an undirected tree |
| Longest path in a DAG / critical path | Relax distances in topological order |
Practice problems
- Course Schedulecycle detectionmedium
- Course Schedule IImedium
- Find All Possible Recipes from Given Suppliesmedium
- Minimum Height Treespeel leavesmedium
- Parallel Coursescount BFS levelsmedium
- Sequence Reconstructionqueue size must be 1medium
- Alien Dictionaryhard
- Longest Increasing Path in a Matrixtopological order by value or memo DFShard
Key takeaways
- Dependencies ⇒ directed graph ⇒ topological sort.
- Kahn's: start from in-degree 0, peel layers; leftover nodes mean a cycle.
- Get the edge direction right.
- Level-by-level processing counts rounds; a min-heap gives the lexicographically smallest order.