Overview
A topological sort orders the vertices of a directed acyclic graph (DAG) so that for every edge u -> v, u comes before v. It answers 'in what order can I do these tasks when some depend on others?' If the graph has a cycle, no valid order exists, which is how you detect impossible dependency chains.
There are two standard algorithms. Kahn's algorithm (BFS) repeatedly removes nodes with in-degree 0. The DFS approach adds each node to the order after all its descendants finish, then reverses. Both run in O(V + E).
Socks before shoes, shirt before tie, trousers before belt. Some items have no dependency and can go first. A topological order is any sequence that never puts shoes on before socks.
When to use it
- Prerequisites, dependencies, build order, task scheduling.
- Detect whether dependencies contain a cycle.
- DP on a DAG: longest path, number of paths, earliest completion time.
- Reconstruct an order from pairwise constraints (alien dictionary).
Problem patterns it solves
Recognize it when: prerequisites might be circular.
- 207. Course Schedule
- 802. Find Eventual Safe States
Recognize it when: return a valid course or build order.
- 210. Course Schedule II
- 1203. Sort Items by Groups Respecting Dependencies
- 2115. Find All Possible Recipes from Given Supplies
Recognize it when: sorted words in an unknown alphabet.
- 269. Alien Dictionary
- 444. Sequence Reconstruction
Recognize it when: longest path, minimum time with parallel tasks.
- 1136. Parallel Courses
- 2050. Parallel Courses III
- 329. Longest Increasing Path in a Matrix
Recognize it when: peel nodes with degree 1 (undirected variant).
- 310. Minimum Height Trees
Where it is used in real software
Make, Gradle, Bazel, and TypeScript project references compile modules in topological order of their imports.
npm, pip, and apt install dependencies before the packages that need them, and report cycles as errors.
Apache Airflow and dbt run tasks as a DAG: each task starts once all its upstream tasks succeed.
Excel recalculates cells in dependency order and reports circular references.
Key terms
- DAG
- Directed acyclic graph: directed edges and no cycles.
- In-degree
- Number of incoming edges; in-degree 0 means no unmet dependencies.
- Kahn's algorithm
- BFS that repeatedly takes in-degree 0 nodes.
- Reverse postorder
- DFS finishing order, reversed, is a topological order.
Kahn's algorithm
- 1Build the graph and in-degrees
For prerequisite [a, b] (b before a): edge b -> a and indegree[a]++.
- 2Queue every in-degree 0 node
They have no remaining dependencies.
- 3Pop a node and append it to the order
It can be done now.
- 4Decrease neighbors' in-degrees
When a neighbor reaches 0, all its dependencies are done: enqueue it.
- 5Check the count
If the order contains fewer than V nodes, the remaining ones are in a cycle.
Course schedule with 4 courses
prerequisites = [[1,0], [2,0], [3,1], [3,2]] (0 before 1 and 2; 1 and 2 before 3)
| Step | Pop | In-degree updates | Queue after | Order so far |
|---|---|---|---|---|
| Start | - | in-degrees: 0:0, 1:1, 2:1, 3:2 | [0] | [] |
| 1 | 0 | 1 -> 0, 2 -> 0 | [1, 2] | [0] |
| 2 | 1 | 3 -> 1 | [2] | [0, 1] |
| 3 | 2 | 3 -> 0 | [3] | [0, 1, 2] |
| 4 | 3 | - | [] | [0, 1, 2, 3] |
NOWStep: Start | Pop: - | In-degree updates: in-degrees: 0:0, 1:1, 2:1, 3:2 | Queue after: [0] | Order so far: []
All 4 courses were ordered, so there is no cycle. [0, 2, 1, 3] would also be valid: topological orders are usually not unique.
Implementation
// 210. Course Schedule II with Kahn's algorithmfunction findOrder(numCourses, prerequisites) { const graph = Array.from({ length: numCourses }, () => []); const indegree = new Array(numCourses).fill(0); for (const [course, pre] of prerequisites) { graph[pre].push(course); indegree[course]++; } const queue = []; for (let i = 0; i < numCourses; i++) if (indegree[i] === 0) queue.push(i); const order = []; for (let head = 0; head < queue.length; head++) { const node = queue[head]; order.push(node); for (const next of graph[node]) { if (--indegree[next] === 0) queue.push(next); } } return order.length === numCourses ? order : []; // [] means a cycle} // DFS version: reverse postorderfunction topoSortDFS(n, graph) { const state = new Array(n).fill(0); // 0 new, 1 visiting, 2 done const order = []; function visit(u) { if (state[u] === 1) throw new Error("cycle"); if (state[u] === 2) return; state[u] = 1; for (const v of graph[u]) visit(v); state[u] = 2; order.push(u); // added after all descendants } for (let i = 0; i < n; i++) visit(i); return order.reverse();}Complexity and performance
Each node and edge processed once.
Graph, in-degrees, and queue.
Order shorter than V means a cycle.
Trade-offs
Kahn's algorithm is iterative, detects cycles by counting, and naturally processes nodes level by level (useful for parallel scheduling). DFS is shorter when you already have DFS code.
Replace Kahn's queue with a min-heap to always pick the smallest available node, at O((V + E) log V).
Variants and related techniques
Process Kahn's queue level by level; the number of levels is the minimum number of semesters (Parallel Courses).
Relax edges in topological order: dist[v] = max(dist[v], dist[u] + w). This is O(V + E), unlike general graphs.
ways[v] += ways[u] in topological order.
Common mistakes
- Reversing edge direction.
Fix: For [a, b] meaning b must come before a, the edge is b -> a.
- Returning a partial order when a cycle exists.
Fix: Check order.length === V.
- Alien dictionary edge cases.
Fix: A longer word appearing before its own prefix ("abc" before "ab") is invalid.
Interview questions
Why does a topological order exist only for DAGs?
In a cycle, every node depends on another node in the cycle, so none can be placed first. Conversely, every DAG has at least one node with in-degree 0 to start from.
How do you find the minimum number of semesters to finish all courses?
Run Kahn's algorithm level by level; each level is one semester, and the answer is the number of levels if all courses are processed.
Practice problems
| Problem | Difficulty | What it trains |
|---|---|---|
| 207. Course Schedule | Medium | Cycle detection. |
| 210. Course Schedule II | Medium | Produce the order. |
| 2115. Find All Possible Recipes from Given Supplies | Medium | Kahn with string nodes. |
| 310. Minimum Height Trees | Medium | Leaf trimming. |
| 2050. Parallel Courses III | Hard | DP over topological order. |
| 269. Alien Dictionary | Hard | Build edges from comparisons. |