Skip to main content
TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN

Topological Sort (Kahn's Algorithm): DAG Ordering & Cycles

Schedule directed prerequisites and detect circular dependencies in O(V + E) using indegree counts.

topological sortgraphsdagpipelinescycles

The core idea

Track each node's remaining prerequisite count (indegree). Enqueue everything at indegree 0; completing a stage unlocks downstream stages whose indegree drops to 0.

Watch it run

Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.

LOADING TOPOLOGICAL SORT DAG SIM...

What to say out loud

Canonical Python template

from collections import deque

def topo_order(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
    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 []

Related Lab Entries