ENع
←Topological sort
Lesson 22 · Graph algorithms

Topological sort

14 min10 steps5 questionsIntermediate
About this lesson

Some jobs have to wait for others: socks before shoes, a library before the program that uses it, a course before the course that needs it. A topological sort lists the jobs so that every "comes first" arrow points forward. Step through Kahn's algorithm on six getting-dressed jobs: count the arrows into each job, queue the jobs at 0, and cross out arrows as jobs are written down. Then add one wrong arrow and watch the run stop short, which is how the algorithm spots a cycle. The Software lessons "Graphs" and "Graph search: BFS and DFS" and the Maths lesson "Graph theory: vertices, edges and breadth-first search" cover directed graphs, queues and depth-first search; "DFS in depth: discovery times and cycle detection" shows the depth-first way to the same answer.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 22 · Interactive
01 / 10

Jobs with arrows

Getting dressed is six jobs. An arrow from socks to shoes means socks must come first. Arrows that point one way, with no loop back, form a DAG: a directed acyclic graph. We want a list of jobs where every arrow points forward.

a DAG: directed edges, no directed cycle
u -> v means "u before v"
  socks  -> shoes
  pants  -> shoes
  pants  -> belt
  shirt  -> belt
  shirt  -> jacket
  belt   -> jacket

the same graph in Python (each job lists the jobs that wait for it):
graph = {
    "socks": ["shoes"],
    "pants": ["shoes", "belt"],
    "shirt": ["belt", "jacket"],
    "shoes": [],
    "belt": ["jacket"],
    "jacket": [],
}
Loading figure…
or ← →
Read the lesson step by step
  1. Jobs with arrows

    Getting dressed is six jobs. An arrow from socks to shoes means socks must come first. Arrows that point one way, with no loop back, form a DAG: a directed acyclic graph. We want a list of jobs where every arrow points forward.

    a DAG: directed edges, no directed cycle
    u -> v means "u before v"
      socks  -> shoes
      pants  -> shoes
      pants  -> belt
      shirt  -> belt
      shirt  -> jacket
      belt   -> jacket
    
    the same graph in Python (each job lists the jobs that wait for it):
    graph = {
        "socks": ["shoes"],
        "pants": ["shoes", "belt"],
        "shirt": ["belt", "jacket"],
        "shoes": [],
        "belt": ["jacket"],
        "jacket": [],
    }
  2. Count the arrows coming in

    For each job, count the arrows that point into it. That number is its in-degree: how many jobs it still waits for. Socks, pants and shirt wait for nothing (0). Shoes, belt and jacket each wait for 2.

    in-degree = number of arrows coming in
    socks 0 · pants 0 · shirt 0 · shoes 2 · belt 2 · jacket 2
    
    indeg = {u: 0 for u in graph}
    for u in graph:
        for v in graph[u]:
            indeg[v] += 1
  3. Zero means ready

    A job with in-degree 0 can start now. Put every such job in a queue, in the order the graph lists them: socks, pants, shirt. A queue is a line: the first job in is the first job out.

    ready = deque(u for u in graph if indeg[u] == 0)
    ready: [socks, pants, shirt]
    a deque appends and pops at either end in O(1)
    dicts keep insertion order, so the queue starts socks, pants, shirt
  4. Take one, cross out its arrows

    The loop: take the front job and write it down. Socks is first. Then cross out its outgoing arrows: each crossed arrow lowers the count of the job it pointed to. Shoes drops from 2 to 1, so it still waits.

    u = ready.popleft()       # socks
    order.append(u)          # order: [socks]
    for v in graph["socks"]: # shoes
        indeg["shoes"] -= 1  # 2 -> 1, not ready yet
  5. A count hits zero

    Take pants and write it down. Its arrow to shoes is crossed out: shoes drops from 1 to 0, so shoes joins the back of the queue. Its arrow to belt is crossed out too: belt drops from 2 to 1.

    u = pants              order: [socks, pants]
    indeg["shoes"]: 1 -> 0  ready.append("shoes")
    indeg["belt"]:  2 -> 1
    ready: [shirt, shoes]
  6. Shirt frees the belt

    Take shirt. Belt drops from 1 to 0 and joins the queue, behind shoes. Jacket drops from 2 to 1: it still waits for the belt. A job enters the queue only when everything before it is written down.

    u = shirt              order: [socks, pants, shirt]
    indeg["belt"]:   1 -> 0  ready.append("belt")
    indeg["jacket"]: 2 -> 1
    ready: [shoes, belt]
  7. Empty the queue

    Shoes has no outgoing arrows, so taking it changes nothing. Taking belt drops jacket to 0, and jacket is taken last. The queue is empty and all six jobs are written down.

    u = shoes   (no arrows out)
    u = belt    indeg["jacket"]: 1 -> 0  ready.append("jacket")
    u = jacket  (no arrows out)
    order: [socks, pants, shirt, shoes, belt, jacket]
  8. Every arrow points forward

    Number the jobs by their place in the list. Every arrow goes from a smaller number to a bigger one: that is a topological order. It is not the only one. Shirt, socks, pants, belt, shoes, jacket also works.

    topological order: f(u) < f(v) for every arrow u -> v
      socks  1 -> shoes  4
      pants  2 -> shoes  4
      pants  2 -> belt   5
      shirt  3 -> belt   5
      shirt  3 -> jacket 6
      belt   5 -> jacket 6
    
    another valid order: shirt, socks, pants, belt, shoes, jacket
    socks and pants are not joined by an arrow, so either may go first
  9. Linear time: O(V + E)

    Each job enters and leaves the queue once: V = 6 times. Each arrow is counted once and crossed out once: E = 6 arrows. So the work grows like V + E, written O(V + E), the same as one BFS or DFS.

    V = 6 jobs: 6 appends + 6 popleft calls
    E = 6 arrows: 6 "+= 1" + 6 "-= 1"
    each step is O(1) (dict lookup, deque append and popleft)
    total: O(V + E)
  10. A loop means no order

    Add a wrong arrow: jacket before shirt. Now shirt, belt and jacket each wait for another in a loop. No count reaches 0, so the run stops with 3 of 6 jobs written. A short list means the graph has a cycle.

    extra arrow: jacket -> shirt
    loop: shirt -> belt -> jacket -> shirt
    order: [socks, pants, shoes]   (3 of 6)
    left waiting: shirt 1 · belt 1 · jacket 2
    if len(order) < len(graph): raise ValueError("cycle")

Quiz Unlocks after the last step.