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 Algorithms

A 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

  1. Compute the in-degree (number of incoming edges) of every node.
  2. Enqueue every node whose in-degree is 0 — nothing depends on them, they can go first.
  3. Dequeue a node, append it to the order, and delete its outgoing edges.
  4. Each deleted edge decrements the target's in-degree; when a target's in-degree hits 0, enqueue it.
  5. 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.

Topological Sort (Kahn)O(V + E)
Peel nodes with in-degree 0 to get a valid processing order for any DAG.
0
0
1
1
1
2
2
3
2
4
0
5
ABCDEF
in-degreeA:0 B:1 C:1 D:2 E:2 F:0
queue—
order—
Step 1 / 15
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Compute in-degrees: A←0, B←1, C←1, D←2, E←2, F←0.
Python · Graph Algorithms in Code
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 cycle

Behind 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

BestO(V + E)
AverageO(V + E)
WorstO(V + E)
SpaceO(V) for the queue, in-degrees and order

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.