A topological order of a directed graph lists its vertices so that every edge u → v points forward: u appears before v. Such an order exists exactly when the graph is a DAG (directed acyclic graph). Two classic linear-time algorithms produce one: Kahn's algorithm, which repeatedly removes vertices with no remaining prerequisites, and DFS reverse post-order. Topological sorting is how build systems, package managers, spreadsheets and schedulers decide what to do first.
Think of it like
Getting dressed in the morning
Socks before shoes, underwear before trousers, trousers before belt, shirt before tie. Your watch has no constraints at all. There are many valid ways to get dressed, but every one of them respects all of the "before" rules. A topological sort finds one such order. If someone added the rule "shoes before socks", there would be no valid order at all: that is a cycle.
What problem it solves
Model each task as a vertex and each dependency as a directed edge u → v, read as "u must happen before v". A topological order is any schedule that respects every dependency. Running tasks in that order guarantees that when you reach a task, everything it depends on is already done.
- Orders are usually not unique. A DAG with
nvertices and no edges hasn!valid orders. - The order is unique exactly when consecutive vertices in it are joined by edges, i.e. the DAG has a Hamiltonian path. In Kahn's algorithm this shows up as the queue never holding more than one vertex.
- Every vertex appears exactly once, including isolated vertices with no edges at all.
Kahn's algorithm
Kahn's algorithm (1962) is a BFS-like peeling process. A vertex with in-degree 0 has no unmet prerequisites, so it can go first. Remove it, decrement the in-degree of everything it points to, and any vertex whose in-degree drops to 0 becomes ready.
- 1
Count in-degrees
For every edge
u → v, incrementindeg[v]. One pass over the edges. - 2
Seed the queue
Enqueue every vertex with
indeg = 0. These are the tasks that can start right away. - 3
Release a vertex
Dequeue
uand append it to the output. It is now "done". - 4
Update dependents
For each edge
u → v, decrementindeg[v]. If it reaches 0, all ofv's prerequisites are done: enqueuev. - 5
Check the count
When the queue empties, if the output has fewer than
Vvertices, the rest are stuck behind a cycle.
Run it on the DAG with edges 5→2, 5→0, 4→0, 4→1, 2→3, 3→1 (six courses, where an edge means "take this before that"). The visualization above animates the same process on preset graphs, including one with a cycle.
| Step | Dequeue | In-degree updates | Queue after | Order so far |
|---|---|---|---|---|
| Init | none | 0:2, 1:2, 2:1, 3:1, 4:0, 5:0 | [4, 5] | [] |
| 1 | 4 | 0: 2→1, 1: 2→1 | [5] | [4] |
| 2 | 5 | 2: 1→0 (ready), 0: 1→0 (ready) | [2, 0] | [4, 5] |
| 3 | 2 | 3: 1→0 (ready) | [0, 3] | [4, 5, 2] |
| 4 | 0 | no outgoing edges | [3] | [4, 5, 2, 0] |
| 5 | 3 | 1: 1→0 (ready) | [1] | [4, 5, 2, 0, 3] |
| 6 | 1 | no outgoing edges | [] | [4, 5, 2, 0, 3, 1] |
[4, 5, 2, 0, 3, 1] is a valid order.DFS reverse post-order
Run Depth-First Search over the whole graph and append each vertex to a list at the moment it finishes (after all its descendants). Reversing that list gives a topological order. The reason: in a DAG, every edge u → v satisfies fin[v] < fin[u].
Why does that hold? When DFS examines u → v, vertex v is either white (it becomes a descendant of u and finishes first), black (it already finished), or gray. Gray would mean v is an ancestor of u, making u → v a back edge and closing a cycle, which a DAG cannot have. Use the same white, gray and black colors to detect that case and report that no order exists.
On the example above, DFS from vertices 0, 1, …, 5 in order finishes them as 0, 1, 3, 2, 4, 5, so the reverse post-order is [5, 4, 2, 3, 1, 0]. That is a different but equally valid order from Kahn's [4, 5, 2, 0, 3, 1].
Kahn's algorithm
- Iterative, queue-based: no recursion-depth issues
- Cycle check: output size less than
V - Naturally produces "layers" (rounds of parallel work)
- Swap the queue for a min-heap to get the smallest order
- Needs in-degrees, so one extra pass over the edges
DFS reverse post-order
- Short to write if you already have DFS
- Cycle check: an edge to a gray vertex
- Recursive; deep graphs need an explicit stack
- Reuses the same machinery as SCC algorithms
- No easy way to control which valid order you get
Lexicographically smallest order
Some problems ask for the smallest order in dictionary order, or simply for a deterministic one. In Kahn's algorithm the queue holds every vertex that is ready right now, so replacing it with a min-heap always releases the smallest ready vertex. The cost rises to O(V log V + E). On the example above this yields [4, 5, 0, 2, 3, 1].
import heapq
def smallest_topo_order(n: int, adj: list[list[int]]) -> list[int]:
indeg = [0] * n
for u in range(n):
for v in adj[u]:
indeg[v] += 1
heap = [v for v in range(n) if indeg[v] == 0]
heapq.heapify(heap) # always release the smallest ready vertex
order = []
while heap:
u = heapq.heappop(heap)
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 []Dynamic programming on a DAG
A topological order processes each vertex after all of its predecessors. That is precisely the order a dynamic program needs when best[v] depends on best[u] for every edge u → v. One pass in topological order solves problems that are hard or impossible on general graphs. See DP Fundamentals for the general pattern.
| DAG DP | Recurrence over incoming edges | Example |
|---|---|---|
| Longest path | max(best[u] + w) | Critical path of a project, longest chain of tasks |
| Shortest path (any weights) | min(best[u] + w) | Negative edges are fine in a DAG: no Dijkstra needed |
| Number of paths | sum(count[u]) | Ways to reach the exit, number of build orders through a step |
| Earliest start time | max(finish[u]) | Build systems and job schedulers with unlimited workers |
Critical path scheduling
If each task has a duration and you have unlimited workers, a task can finish no earlier than finish[v] = time[v] + max(finish[u]) over its prerequisites u. The whole project takes max(finish), the length of the critical path. Delaying any task on that path delays the project; tasks off the path have slack. The third implementation below computes this.
Applications
- Build systems (Make, Bazel, Gradle): compile each target after its dependencies; independent targets build in parallel.
- Package managers (npm, pip, apt): install dependencies before the packages that need them, and report dependency cycles.
- Spreadsheets: recalculate cells in dependency order after an edit; a circular reference is a cycle.
- Course planning: prerequisites form a DAG; Kahn's levels give a semester-by-semester plan.
- Data pipelines and workflow engines (Airflow DAGs, CI pipelines): run each step when its inputs are ready.
- Compilers: instruction scheduling and ordering of static initializers.
Complexity
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Kahn's algorithm (queue) | O(V + E) | O(V) | Cycle detected when output size < V |
| DFS reverse post-order | O(V + E) | O(V) | Recursion depth up to V |
| Kahn's with a min-heap | O(V log V + E) | O(V) | Lexicographically smallest order |
| DP on a DAG (longest path, counting) | O(V + E) | O(V) | One pass in topological order |
Space excludes the adjacency list itself (O(V + E)).
Implementation
Edge `(u, v)` means `u` must come before `v`. Returns an empty list if the graph has a cycle. On the example DAG it returns `[4, 5, 2, 0, 3, 1]`.
from collections import deque
def topo_sort_kahn(n: int, edges: list[tuple[int, int]]) -> list[int]:
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
queue = deque(v for v in range(n) if indeg[v] == 0) # no unmet prerequisites
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1 # u is done: one fewer prerequisite for v
if indeg[v] == 0:
queue.append(v)
return order if len(order) == n else [] # leftovers sit on or behind a cycle
print(topo_sort_kahn(6, [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]))
# [4, 5, 2, 0, 3, 1]Key takeaways
- A topological order puts
ubeforevfor every edgeu → v; it exists if and only if the graph is a DAG. - Kahn's algorithm peels off in-degree-0 vertices with a queue; outputting fewer than
Vvertices proves a cycle. - DFS reverse post-order works because
fin[v] < fin[u]for every DAG edge; a gray neighbor means a cycle. - A min-heap in place of Kahn's queue yields the lexicographically smallest order in
O(V log V + E). - Processing vertices in topological order enables linear-time DP: longest paths, path counts and critical-path scheduling.
Common pitfalls
- Reversing dependency edges (
[a, b]meaning "bbeforea" must becomeb → a). - Forgetting the cycle check and returning a partial order as if it were complete.
- Using DFS pre-order (discovery order) instead of reverse post-order, which is not a valid topological order in general.
- Detecting cycles in the DFS version with a single visited flag, which misreports harmless cross edges as cycles.
- Omitting isolated vertices (in-degree 0, no edges) from the output.
Interview tips
- Course Schedule I and II are among the most common graph interview questions: be able to write Kahn's algorithm from memory.
- Mention both algorithms and their cycle checks, then pick Kahn's for its iterative simplicity unless DFS is already in play.
- If asked "minimum number of semesters" or "rounds", process Kahn's queue level by level and count the levels.
Real-world applications
- Build systems and incremental compilation (Make, Bazel, Gradle).
- Dependency resolution in package managers.
- Spreadsheet recalculation order and circular-reference detection.
- Workflow orchestration (Airflow, CI/CD pipelines, data pipelines).
- Course and project planning, including critical path analysis.
- Instruction scheduling and symbol resolution in compilers and linkers.
Practice problems
Test yourself
Kahn's algorithm outputs only 4 of a graph's 6 vertices before the queue empties. What does that mean?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.