Topological Sort & Union-Find

Step through Kahn's topological sort, track in-degrees and detect cycles. Explore union-find with interactive graph examples on CodeQuest101.

Order the courses so every prerequisite comes first. The full walkthrough is below.

intro0
data0
algos0
discrete0
os0
compilers0

Ready queue

—

Ordering

—

Step 0 / 14
700 ms

Press Start.

How it works: Topological Sort (Kahn's algorithm)

Step by step

  • Node being output
  • Ready queue (in-degree 0)
  • Already in the order
  • Stuck on a cycle

Press Start or Step: the step the animation is on lights up below.

  1. 1

    Count each node's incoming edges

    One pass over the edges gives every node's in-degree. Nodes at 0 have no prerequisites and start in the ready queue.

    for (u, v) in edges: indeg[v] += 1; ready = [v with indeg 0]
  2. 2

    Output a ready node

    Take a node from the ready queue and append it to the order. Everything it depends on is already in the output.

    u = ready.popleft(); order.append(u)
  3. 3

    Remove its edges → counts drop

    Each outgoing edge was one prerequisite of its target, and that prerequisite is now met. Lower the target's count.

    for v in out[u]: indeg[v] -= 1
  4. 4

    Count hits 0 → node is ready

    A node whose last prerequisite was just met joins the ready queue.

    if indeg[v] == 0: ready.append(v)
  5. 5

    Queue empty → order complete

    Every node was output, so the order respects every edge.

    return order # len(order) == n
  6. 6

    Nodes left over → there's a cycle

    The queue ran dry with nodes still waiting. They depend on each other in a loop, so no valid order exists.

    if len(order) < n: return None # cycle

A topological order lists the nodes of a directed graph so that every edge points forward: each task comes after everything it depends on. It exists exactly when the graph has no cycle.

Kahn's algorithm keeps a count of each node's unmet prerequisites (its in-degree). Any node at zero can go now. Output one, remove its outgoing edges, and some other nodes drop to zero and become ready in turn. Repeat until nothing is ready.

Cycle detection comes for free. Nodes on a cycle wait on each other forever, their counts never reach zero, and the output ends up shorter than the number of nodes.

Spot it in an interview

  • “Course schedule”, “build order”, “task dependencies”, or “alien dictionary” (ordering letters from sorted words).
  • “Can all of these be finished?” That's the same as asking whether the graph is acyclic.
  • Any “X must happen before Y” rules that you need to turn into a sequence.
time O(V + E)space O(V + E)

Every node enters and leaves the queue once, and every edge is followed once to decrement a count. That's linear in the graph's size. The adjacency list and the counts take O(V + E).