Topological sort: an order that respects dependencies
Given rules like "A before C", you need one order that breaks none of them, or proof that none exists. Count what each item still waits for, keep taking the ones that wait for nothing, and a cycle shows up as the items left behind.
01 An order that breaks no rule
You have six courses and a list of rules like "take A before C". Build tools have the same problem with targets, package managers with dependencies, spreadsheets with formulas that read other cells. You want a single line-up in which everything comes after the things it depends on.
That line-up is a topological order. Draw each rule as an arrow, and the order is one where every arrow points forward. Sorting by name or number cannot find it, because the rules only compare some pairs: A and B have no rule between them at all.
- course
Each tag is the node's in-degree: the number of arrows pointing into it. E needs both C and D, so it starts at 2.
02 Start with what needs nothing
Something has to go first, and it must be a node with no arrows coming in. Place it, then pretend its outgoing arrows are gone: each node it pointed to now waits for one thing fewer. Any node whose count reaches 0 is free to go next. Repeat until nothing is left.
This is Kahn's algorithm. It never searches for a valid order; it just keeps a queue of nodes whose count is 0 and works through it. The counts do all the bookkeeping.
03 Kahn's algorithm, step by step
- still waiting
- just became ready
- ready, in the queue
- taken and placed
- placed
- edge used up
Each node is tagged with its in-degree: how many prerequisites it still waits for. Nothing is ready or placed yet.
Each node enters the queue exactly once, at the moment its count hits 0, and each edge is used up exactly once. So the whole run is O(V + E) for V nodes and E edges.
04 A cycle leaves nodes behind
If the rules go round in a circle, there is no valid order: each node in the circle must come after another one in it. Kahn's algorithm notices this for free.
- still waiting
- just became ready
- taken and placed
- placed
- edge used up
- edge in the cycle
B needs A and D; C needs B; D needs C; E needs D. Only A has in-degree 0.
So the cycle check is one comparison at the end: if fewer nodes were placed than exist, there is a cycle, and the unplaced nodes are the cycle plus everything downstream of it. That is the whole of Course Schedule: return whether all courses got placed.
05 The code
Build the adjacency list and the counts in one pass over the edges, seed the queue with every count of 0, and run the loop.
That is the real output of python3 topo.py (Python 3.14): the six-course order from the trace, then None for the graph with the cycle.
06 More than one right answer
Rules only fix some pairs, so there are usually several valid orders. Which one you get depends on which ready node you take first.
| Order | Valid? | Why |
|---|---|---|
| A B C D E F | Yes | What the queue produced. |
| B D A C E F | Yes | Also respects every arrow; a stack instead of a queue gives orders like this. |
| B A D C E F | Yes | A and B have no rule between them, nor do C and D. |
| A C B D E F | No | C comes before B, but the rule B → C says B goes first. |
If you need one particular order, such as the alphabetically smallest, replace the queue with a min-heap so the smallest ready node always goes next. The cost becomes O((V + E) log V).
07 When it bites
for course, pre in prerequisites:Arrows the wrong way roundCourse Schedule gives pairs [a, b] meaning b before a. Add the edge b → a. Flip it and you get the order reversed, and the cycle check still passes, so the bug hides.nodes = {a for a, b in edges} | {b for a, b in edges}Losing nodes with no edgesA course with no rules never appears in the edge list. Build the counts from the full list of nodes, or it is silently left out of the order.return orderSkipping the cycle checkWith a cycle the loop just ends early and returns a partial order that looks fine. Compare len(order) with the number of nodes.min(n for n in todo if need[n] == 0)Rescanning for the next ready nodeSearching all nodes each round is O(V²). The queue already holds exactly the ready ones; update counts only along the edges you use up.