Kodewick
Start learning →
Topological sort33 / 52

Topological sort

Lesson 33 of 52 · Part 6 · Graphs · about 16 minutes

A topological sort orders vertices so that each comes after everything it depends on; Kahn's algorithm enqueues the vertices with in-degree 0, lowers their neighbours' in-degrees as each is dequeued, and if fewer than n come out, the graph has a cycle.

University courses come with prerequisites: before "Algorithms" you need "Data structures" and "Discrete maths", and before "Data structures" you need Python. When you pip install a package, the packages it depends on have to be installed first; when make builds a project, the files others include are compiled first. All of these need an order where everything comes after everything it depends on. That is a topological sort. With BFS's queue plus a count of "in-degrees" it takes a dozen lines, O(n + e), and on the way it answers a more urgent question: do these dependencies go round in a circle, so that no order exists at all?

In-degree 0 goes first

Draw each dependency as a directed edge: "u before v" is u → v. A vertex's in-degree is how many things it is still waiting for. A vertex with in-degree 0 waits for nobody and can go first.

Kahn's algorithm:

  1. Count each vertex's in-degree.
  2. Enqueue every vertex with in-degree 0.
  3. Dequeue u and add it to the result; u is done, so each v it points to waits for one thing fewer: indeg[v] -= 1, and when that reaches 0, enqueue v.
  4. Stop when the queue is empty.

Queue

The number on a vertex is its remaining in-degree: B waits for nobody and goes first; each vertex that leaves lowers the in-degree of those it points to, and any that reach 0 join the queue
main.py
1from collections import deque2 3graph = {4    "A": ["D"],5    "B": ["A", "C"],6    "C": ["D", "E"],7    "D": ["F"],8    "E": ["F"],9    "F": [],10}11 12def topo_sort(graph):13    indeg = {u: 0 for u in graph}14    for u in graph:15        for v in graph[u]:16            indeg[v] += 117    q = deque(u for u in graph if indeg[u] == 0)18    order = []19    while q:20        u = q.popleft()21        order.append(u)22        for v in graph[u]:23            indeg[v] -= 1                # u is done: v waits for one thing fewer24            if indeg[v] == 0:25                q.append(v)26    return order27 28print(topo_sort(graph))29order = topo_sort(graph)30pos = {u: i for i, u in enumerate(order)}31print("every edge points forwards:", all(pos[u] < pos[v] for u in graph for v in graph[u]))
Output
['B', 'A', 'C', 'D', 'E', 'F']
every edge points forwards: True

Counting the in-degrees looks at every edge once, and the dequeues look at every edge once more: time O(n + e), space O(n).

A topological order is not always unique: after B, either A or C can come first, as long as both come before D. The result this step's program prints comes from the queue's order and the order the neighbours are stored in; when a problem needs one particular answer, it adds a rule (such as "smallest first", in "How you write it at work" below).

Choose one

Which set of prerequisites can't be put in any order?

Choose one

Directed edges B → A, B → D, C → A, A → E, D → E. Run Kahn's algorithm, queueing vertices in alphabetical order when several reach in-degree 0 together. What order comes out?

Choose one

The six-course graph: edges 0 → 2, 1 → 2, 0 → 3, 2 → 4, 1 → 4, 2 → 5, 3 → 5. Which one is not a topological order?

A cycle means no order

If F were also a prerequisite of C (F → C), there would be a circle: C waits for F, F waits for D, and D waits for C. The in-degrees on the circle never drop to 0, so those vertices never join the queue. That makes the cycle test one line: if fewer vertices come out than there are, there is a cycle.

Queue

Add F → C and C, D, F form a cycle: once B and A have left, the queue is empty, and the in-degrees left never reach 0
main.py
1from collections import deque2 3def topo_sort(graph):4    indeg = {u: 0 for u in graph}5    for u in graph:6        for v in graph[u]:7            indeg[v] += 18    q = deque(u for u in graph if indeg[u] == 0)9    order = []10    while q:11        u = q.popleft()12        order.append(u)13        for v in graph[u]:14            indeg[v] -= 115            if indeg[v] == 0:16                q.append(v)17    return order, indeg18 19graph = {"A": ["D"], "B": ["A", "C"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": ["C"]}20order, indeg = topo_sort(graph)21print("sorted:", order)22print("cycle:", len(order) < len(graph))23print("stuck:", [u for u in graph if indeg[u] > 0])
Output
sorted: ['B', 'A']
cycle: True
stuck: ['C', 'D', 'E', 'F']

The stuck ones are C, D, E and F: C, D and F on the circle, plus E behind it (it waits for C). The vertices left with an in-degree above 0 are exactly those "held up by the cycle"; list them in the error message so the user knows what to fix.

Guess the outputA wrong guess is fine

2 → 3 → 4 → 2 is a circle. What does it print?

1from collections import deque2 3graph = {1: [2], 2: [3], 3: [4], 4: [2], 5: [1]}4indeg = {u: 0 for u in graph}5for u in graph:6    for v in graph[u]:7        indeg[v] += 18q = deque(u for u in graph if indeg[u] == 0)9order = []10while q:11    u = q.popleft()12    order.append(u)13    for v in graph[u]:14        indeg[v] -= 115        if indeg[v] == 0:16            q.append(v)17print(order, len(order) == len(graph))
Exercise 1

Can all the courses be finished?

Complete can_finish(n, prereq): n courses are numbered 0 to n − 1, and (a, b) in prereq means b must be taken before a. Return True if an order exists, False if there is a cycle.

It should print
True
False
False
True
exercise1.py
1from collections import deque2 3def can_finish(n, prereq):4    graph = [[] for _ in range(n)]5    indeg = [0] * n6    # build the graph: b -> a, a's in-degree goes up by one; then run Kahn and count what comes out7    return False8 9print(can_finish(2, [(1, 0)]))10print(can_finish(2, [(1, 0), (0, 1)]))11print(can_finish(4, [(1, 0), (2, 1), (3, 2), (1, 3)]))12print(can_finish(3, []))
Output
Press Run or Ctrl+Enter

Course schedule: the fewest terms

Scheduling courses is the most common form of topological sort (LeetCode 207 and 210, Course Schedule). The input is usually a list of (course, prerequisite) pairs; build the graph first, prerequisite → course.

Now one more question: if you can take any number of courses in a term, what is the fewest number of terms? Run Kahn's algorithm dequeueing by layers (the layer-by-layer BFS of the last lessons): courses in the same layer don't depend on each other and can share a term, and the number of layers is the fewest terms.

TermTaken this term (in-degree 0)Dropped to in-degree 0 afterwards
1Python basics, Discrete mathsData structures (Algorithms still waits for Data structures)
2Data structuresAlgorithms, Databases
3Algorithms, DatabasesCompilers
4Compilersnone left: all 6 scheduled, no cycle
6 courses dequeued by layer: each layer is one term, and only after it is done do the next layer's in-degrees reach 0
main.py
1from collections import deque2 3names = ["Python basics", "Discrete maths", "Data structures", "Algorithms", "Databases", "Compilers"]4prereq = [(2, 0), (3, 2), (3, 1), (4, 2), (5, 3), (5, 4)]     # (course, prerequisite)5 6def plan(n, prereq):7    graph = [[] for _ in range(n)]8    indeg = [0] * n9    for course, pre in prereq:10        graph[pre].append(course)        # prerequisite -> course11        indeg[course] += 112    q = deque(i for i in range(n) if indeg[i] == 0)13    terms = []14    done = 015    while q:16        term = []17        for _ in range(len(q)):          # pop only this layer18            u = q.popleft()19            term.append(u)20            done += 121            for v in graph[u]:22                indeg[v] -= 123                if indeg[v] == 0:24                    q.append(v)25        terms.append(term)26    if done < n:27        return None                      # a cycle: no schedule28    return terms29 30for i, term in enumerate(plan(6, prereq), 1):31    print(f"term {i}:", [names[c] for c in term])32print(plan(3, [(0, 1), (1, 2), (2, 0)]))
Output
term 1: ['Python basics', 'Discrete maths']
term 2: ['Data structures']
term 3: ['Algorithms', 'Databases']
term 4: ['Compilers']
None
MethodTimeWhat it gives
Kahn (in-degrees + a queue)O(n + e)an order; fewer than n means a cycle; dequeueing by layers gives the fewest terms
Kahn + heapqO(n log n + e)the smallest number each time: the lexicographically smallest order
DFS postorder, reversedO(n + e)also a topological order; detecting a cycle needs three colours (the "still on the stack" of the last lesson)

In interviews: "course schedule", "task scheduling", "build order", "alien dictionary" are all topological sorts. Say first how you build the graph (edges from what comes first to what comes later) and count the in-degrees, then "fewer than n out means a cycle". Asked "is the order unique?": only when the queue holds a single vertex at every step.

Guess the outputA wrong guess is fine

4 courses: 1 and 2 both need 0 first, and 3 needs 1 and 2. Taking it level by level, what is the fewest number of terms?

1from collections import deque2 3n = 44prereq = [(1, 0), (2, 0), (3, 1), (3, 2)]5graph = [[] for _ in range(n)]6indeg = [0] * n7for course, pre in prereq:8    graph[pre].append(course)9    indeg[course] += 110q = deque(i for i in range(n) if indeg[i] == 0)11terms = 012while q:13    terms += 114    for _ in range(len(q)):15        u = q.popleft()16        for v in graph[u]:17            indeg[v] -= 118            if indeg[v] == 0:19                q.append(v)20print(terms)
Choose one

The six-course graph, edges 0 → 2, 1 → 2, 0 → 3, 2 → 4, 1 → 4, 2 → 5, 3 → 5, done with DFS: starting at 0, neighbours smallest first, the vertices finish (return) in the order 4 5 2 3 0 1. What topological order does that give?

Exercise 2

An order to take the courses

Complete find_order(n, prereq): the same input as the last exercise; return an order to take the courses, and among courses that can be taken at the same time, take the smaller number first (use heapq). Return an empty list when there is a cycle.

It should print
[0, 1, 2, 3]
[3, 2, 4, 0, 1]
[]
exercise2.py
1import heapq2 3def find_order(n, prereq):4    order = []5    # build the graph and count in-degrees; in-degree-0 courses go on a heap, pop the smallest each time6    return order7 8print(find_order(4, [(1, 0), (2, 0), (3, 1), (3, 2)]))9print(find_order(5, [(0, 4), (1, 4), (2, 3)]))10print(find_order(2, [(0, 1), (1, 0)]))
Output
Press Run or Ctrl+Enter

How you write it at work

Since Python 3.9 the standard library has graphlib.TopologicalSorter: give it each node's predecessors and static_order() returns an order, raising graphlib.CycleError on a cycle; inside, it is Kahn's algorithm too. It is not available in this course's practice environment, so below it is written by hand as before.

When a problem wants "among the things that can be done now, do the smallest number first", swap the deque for heapq: each pop gives the smallest of the vertices currently at in-degree 0, and the result is the lexicographically smallest topological order.

main.py
1import heapq2 3def smallest_order(n, edges):4    graph = [[] for _ in range(n)]5    indeg = [0] * n6    for u, v in edges:7        graph[u].append(v)8        indeg[v] += 19    heap = [i for i in range(n) if indeg[i] == 0]10    heapq.heapify(heap)11    order = []12    while heap:13        u = heapq.heappop(heap)          # the smallest of those that can go now14        order.append(u)15        for v in graph[u]:16            indeg[v] -= 117            if indeg[v] == 0:18                heapq.heappush(heap, v)19    return order if len(order) == n else None20 21edges = [(3, 1), (4, 1), (1, 0), (4, 2)]22print(smallest_order(5, edges))23print(smallest_order(2, [(0, 1), (1, 0)]))
Output
[3, 4, 1, 0, 2]
None

Each push and pop on the heap is O(log n), so the total is O(n log n + e). When the order doesn't have to be the smallest, a deque is enough.

Guess the outputA wrong guess is fine

heapq instead of deque: of the things that can be done now, the smallest number goes first. What does this print?

1import heapq2 3n = 44edges = [(3, 1), (0, 2)]5graph = [[] for _ in range(n)]6indeg = [0] * n7for u, v in edges:8    graph[u].append(v)9    indeg[v] += 110heap = [i for i in range(n) if indeg[i] == 0]11heapq.heapify(heap)12order = []13while heap:14    u = heapq.heappop(heap)15    order.append(u)16    for v in graph[u]:17        indeg[v] -= 118        if indeg[v] == 0:19            heapq.heappush(heap, v)20print(order)

Summary

Take-away

Topological sort: in-degree 0 goes first

  • Edges point from what comes first to what comes later; in-degree = how many things it still waits for
  • Kahn: in-degree-0 vertices go in a deque; each dequeue lowers its neighbours' in-degrees, and those at 0 join
  • Fewer than n out means a cycle; whatever keeps an in-degree above 0 is stuck
  • Dequeue by layers for the fewest terms; swap in heapq for the smallest order
  • Time O(n + e); the order may not be unique
1q = deque(u for u in graph if indeg[u] == 0)2while q:3    u = q.popleft(); order.append(u)4    for v in graph[u]:5        indeg[v] -= 16        if indeg[v] == 0: q.append(v)