Topological sort: ordering tasks with dependencies
Ordering the nodes of a directed graph so every prerequisite comes first, and detecting cycles at the same time. The engine behind build systems and "Course Schedule".
In short
In a directed acyclic graph (DAG) a topological order puts every node after its prerequisites. Kahn's algorithm: repeatedly take a node with in-degree 0, remove it, and lower its neighbours' in-degree. If you can't order all nodes, there is a cycle. Cost: O(V + E).
Kahn's algorithm in action
Edges read as "must come before". The number under each node is how many prerequisites are still pending. Run the cycle example to see how the algorithm gets stuck.
queue (in-degree 0)
topological order
1def topo_sort(n, edges):2 indeg = [0] * n; adj = [[] for _ in range(n)]3 for a, b in edges:4 adj[a].append(b); indeg[b] += 15 queue = deque(i for i in range(n) if indeg[i] == 0)6 order = []7 while queue:8 node = queue.popleft()9 order.append(node)10 for nb in adj[node]:11 indeg[nb] -= 112 if indeg[nb] == 0:13 queue.append(nb)14 return order if len(order) == n else []
Variables
What to remember
- Directed graph with no cycles is the precondition. A cycle (A needs B needs A) has no valid order.
- Cycle detection for free: if the output has fewer nodes than the graph, a cycle exists.
- Many valid orders: any node of in-degree 0 may go next; a problem may ask for any one, or the lexicographically smallest (use a min-heap instead of a queue).
- DFS alternative: do a DFS and push each node *after* visiting all its descendants; the reverse of that list is a topological order. A back edge to a node on the current path means a cycle.
| Problem | Nodes | Edge a → b |
|---|---|---|
| Course Schedule I / II | Courses | a is a prerequisite of b |
| Build order | Packages | a must be built before b |
| Alien dictionary | Letters | a comes before b in the alien alphabet |
Key takeaways
- 01Topological order = every node after its prerequisites; only DAGs have one.
- 02Kahn: queue the in-degree-0 nodes, remove them, update neighbours.
- 03Fewer ordered nodes than total means a cycle.
- 04O(V + E) time and space.
Check your understanding
1 of 3
Which graphs have a topological order?
Related topics
BFS & DFS
A graph is nodes and edges. BFS uses a queue and explores in rings: the first time it reaches a node is via a shortest path (unweighted). DFS uses a stack (or recursion) and dives deep. Both cost O(V + E). Always keep a visited set, or cycles will loop forever.
10 min read →Stacks & queues
A stack gives back the most recent item first (LIFO); a queue gives back the oldest first (FIFO). Both do push and pop in O(1). Nested structure → stack. Processing in order of arrival → queue.
7 min read →