Animation10 min

Topological Sort

Ordering tasks by prerequisites, and detecting impossible cycles.

A topological sort is an ordering of tasks such that every prerequisite comes before the task that needs it. This animation shows Kahn's algorithm — the repeatedly-take-what's-ready method — on a set of course cards connected by prerequisite arrows. Each card wears an indegree badge: a count of how many unfinished prerequisites still point at it.

Each tick, every card whose badge reads zero glows — nothing blocks it — and one slides down into a growing schedule timeline. As it locks in, its outgoing arrows dissolve, and each downstream card's badge decrements with a tick. Newly-zeroed cards glow next, and the timeline grows left to right.

What to watch for:

  • Only zero-badge cards ever move. A card enters the schedule exactly when its last prerequisite resolves — that's the whole correctness argument.
  • Ties mean choice. When several cards glow at once, any of them may go next — valid orderings are rarely unique.
  • The failure mode. In the cycle demo, cards remain but none has a zero badge: each waits on another in a loop. The leftover cycle lights up red and rotates. Scheduled count < total count is exactly how code detects an impossible (cyclic) dependency graph.