Pattern #20
Topological Sort
AdvancedOrder nodes so every directed edge goes from earlier to later.
When to use
Prerequisites, build order, or any DAG dependency constraints.
Recognition cues
- Course schedule / order
- Alien dictionary
- Indegree queue (Kahn) or DFS postorder
Common pitfalls
- Not detecting cycles (incomplete order)
- Building the graph in the wrong direction
- Multiple valid orders: any is fine unless specified
90-second recognition drill
Which pattern fits best?
- Course schedule / order
- Alien dictionary
- Indegree queue (Kahn) or DFS postorder
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
Step 1 of 8
Statequeue=[A]order=[]
indegree A0 B1 C1 D2
How to think about it
In a DAG, nodes with indegree 0 can come first. Kahn’s algorithm: queue them, emit, reduce neighbors’ indegrees. If you emit fewer than n nodes, a cycle exists. DFS variant: add node to front after exploring children.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Cycle check | Kahn: queue every node with indegree 0, pop it, and reduce its neighbors. Popping every node means there is no cycle | LC 207 |
| Course order | The same Kahn queue. The pop order is a valid order. A cycle leaves a node unpopped, and the answer is empty | LC 210 |
| Alien order | The first differing character between adjacent words is one precedence edge. A longer word listed before a word that is its prefix is invalid. Kahn orders the letters. A cycle returns an empty string | LC 269 |
| Minimum height | Peel degree-1 leaves the way Kahn peels indegree 0. Stop when 1 or 2 nodes remain. n = 1 returns [0] |
LC 310 |
| Semesters | Each Kahn layer is one semester. The number of layers is the answer. A leftover node is a cycle | LC 1136 |
| Groups and items | Two Kahn sorts: items under beforeItems, and groups. A cycle in either graph returns empty. Group order concatenates the item lists. A group id of -1 becomes its own group |
LC 1203 |
Complexity baseline
O(V+E) time and space.
From template to problem
- Point each edge from the prerequisite to the later node, then fill indegrees.
- Kahn pops indegree 0. Emitting every node means there is no cycle (LC 207). The pop order is the course order, and a cycle returns empty (LC 210).
- An alien dictionary takes one edge at the first differing character. A longer word before its own prefix is invalid before Kahn runs (LC 269).
- Layers of that queue are semesters (LC 1136). Items and groups are two graphs, and either cycle returns empty (LC 1203). A group id of -1 becomes its own group before the edges are built.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Topological Sort · Template
/** Topo template: Kahn BFS; empty array if cycle. */
export function topoSort(n: number, edges: number[][]): number[] {
const g: number[][] = Array.from({ length: n }, () => []);
const indeg = new Array(n).fill(0);
for (const [u, v] of edges) {
g[u!]!.push(v!);
indeg[v!]++;
}
const q: number[] = [];
for (let i = 0; i < n; i++) if (indeg[i] === 0) q.push(i);
const order: number[] = [];
while (q.length) {
const u = q.shift()!;
order.push(u);
for (const v of g[u]!) if (--indeg[v]! === 0) q.push(v);
}
return order.length === n ? order : [];
}
/** Topo template: Kahn BFS; empty array if cycle. */
export function topoSort(n: number, edges: number[][]): number[] {
const g: number[][] = Array.from({ length: n }, () => []);
const indeg = new Array(n).fill(0);
for (const [u, v] of edges) {
g[u!]!.push(v!);
indeg[v!]++;
}
const q: number[] = [];
for (let i = 0; i < n; i++) if (indeg[i] === 0) q.push(i);
const order: number[] = [];
while (q.length) {
const u = q.shift()!;
order.push(u);
for (const v of g[u]!) if (--indeg[v]! === 0) q.push(v);
}
return order.length === n ? order : [];
}
#StatusProblemTypeDifficultyDone
- 1#207 Course ScheduleGuidemedium
- 2#210 Course Schedule IIGuidemedium
- 3#269 Alien DictionaryGuidehard
- 4#310 Minimum Height TreesGuidemedium
- 5#1136 Parallel CoursesGuidemedium
- 6#1203 Sort Items by Groups Respecting DependenciesGuidehard