Algorithms · Visualized
Topological Sort (Kahn)
Graph Algorithms
Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.
A topological order of a directed acyclic graph lists nodes so that every edge points forward — prerequisites always come before dependents. Time: O(V + E) average, O(V + E) worst; space: O(V) for the queue, in-degrees and order.
Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).
Topological Sort (Kahn's Algorithm)
Graph AlgorithmsA topological order of a directed acyclic graph lists nodes so that every edge points forward — prerequisites always come before dependents. Kahn's algorithm repeatedly removes nodes with in-degree 0 (nothing left pointing at them), appends them to the order, and decrements the in-degrees of their targets. If the process stalls before all nodes are output, a cycle exists and no valid order is possible.
How Topological Sort (Kahn) Works
- Compute the in-degree (number of incoming edges) of every node.
- Enqueue every node whose in-degree is 0 — nothing depends on them, they can go first.
- Dequeue a node, append it to the order, and delete its outgoing edges.
- Each deleted edge decrements the target's in-degree; when a target's in-degree hits 0, enqueue it.
- If the final order contains fewer than all nodes, the leftover nodes form a cycle.
Topological Sort (Kahn) Worked Example
Input: {graph: A→B, A→C, B→D, C→D, C→E, D→E, start: —}
In-degrees: A←0, B←1, C←1, D←2, E←2. Queue starts [A]. Output A → B, C drop to 0 → both enqueue. Output B → D drops to 1. Output C → D hits 0 (enqueue), E drops to 1. Output D → E hits 0. Output E. Order: A B C D E.
from collections import deque
def topo_sort(n, edges):
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 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 None # None means cycleBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Topological Sort (Kahn) Time & Space Complexity
When to Use Topological Sort (Kahn)
- Build systems and package managers: compile dependencies before dependents.
- Course prerequisite planning, task scheduling with dependencies, spreadsheet formula evaluation.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.