Skip to content

Topological sort: an order that respects dependencies

Working knowledgeUnder the hood

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.

Six courses; an arrow from A to C means take A before C
Course graph · arrow = comes before
Ain 0
Bin 0
Cin 2
Din 1
Ein 2
Fin 1
  • 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

Kahn's algorithm on six courses
Step 1 of 8
Course graph · arrow = comes before
Ain 0
Bin 0
Cin 2
Din 1
Ein 2
Fin 1
Ready · front first
Empty
Order
Empty
  • 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.

0 of 6 placed

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.

A cycle stops the queue
Step 1 of 4
Graph with a cycle B → C → D → B
Ain 0
Bin 2
Cin 1
Din 1
Ein 1
Ready · front first
Empty
Order
Empty
  • 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.

0 of 5 placed

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.

topo.py
from collections import deque
def topo_order(nodes, edges):
after = {n: [] for n in nodes} # a -> what a unlocks
need = {n: 0 for n in nodes} # remaining prerequisites
for a, b in edges: # a must come before b
after[a].append(b)
need[b] += 1
ready = deque(n for n in nodes if need[n] == 0)
order = []
while ready:
n = ready.popleft()
order.append(n)
for m in after[n]:
need[m] -= 1 # one prerequisite done
Text
['A', 'B', 'C', 'D', 'E', 'F']
None

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.

Some orders for the six courses
OrderValid?Why
A B C D E FYesWhat the queue produced.
B D A C E FYesAlso respects every arrow; a stack instead of a queue gives orders like this.
B A D C E FYesA and B have no rule between them, nor do C and D.
A C B D E FNoC 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).

Kahn · queue of in-degree 0Placed front to backIterative, and the cycle check is a count. Easy to see which nodes are ready at any moment, which suits schedulers running jobs in parallel.
DFS · finish timesPlaced back to frontRun a depth-first search and record each node when all its descendants are finished; reverse that list. Cycle detection needs a third colour for "on the current path".

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.

08 Check yourself

Question

Edges are X → Y, X → Z, Y → Z. Which order is valid?

Question

Kahn's algorithm stops with 4 of 7 nodes placed. What can you say?

Question

Why does every node enter the queue at most once?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?