Lesson 4 of 6
Dependencies and topological sort
When tasks wait on other tasks, a topological order runs each task after everything it waits for. Kahn's algorithm builds one by counting what each task still waits for and releasing a task the moment that count reaches 0, and it spots a cycle when tasks are left over.
Check whether an order puts every task after the tasks it waits for
Build a list of dependents and a list of in-degrees from a list of arrows
Trace Kahn's algorithm and say the queue, the in-degrees and the order after each step
Detect a cycle by counting the tasks that come out
Solve Course Schedule and Course Schedule II in O(V + E) time
Your nightly pipeline has five jobs. orders and prices load raw tables. clean reads orders. priced joins orders with prices. report reads clean and priced. In what order can the jobs run, one at a time?
You can work this one out in your head: the two loads, then clean and priced, then report. Airflow and dbt work it out for you every night, for hundreds of jobs. In an interview, you write the part they do. Candidates report that topological sort and dependency order is one of the question families that keeps coming up. The classic version is about courses with prerequisites.
This lesson builds the algorithm from one question you can ask at any moment: which job can run right now?
An order where every arrow points forward
What makes an order correct? Write each dependency as an arrow from the job that must go first to the job that waits: orders → clean. Jobs joined by arrows form a directed graph. Reminder: a graph is a set of things, called nodes, joined by edges; directed means every edge has a direction, so it is drawn as an arrow.
Course Schedule, the classic interview version, numbers its tasks from 0, and so will we. The numbers are only labels: they say nothing about the order.
| task | job | waits for |
|---|---|---|
| 0 | report | 1 and 2 |
| 1 | clean | 3 |
| 2 | priced | 3 and 4 |
| 3 | orders | nothing |
| 4 | prices | nothing |
Each task named in the "waits for" column is one arrow, into the task on its row. The column names five tasks, so the pipeline has five arrows. We write an arrow as a pair [before, after]. Listed in any order, the pipeline's arrows are [[3, 1], [1, 0], [3, 2], [2, 0], [4, 2]]: orders feeds clean, clean feeds report, and so on.
A topological order lists every task once, so that every arrow points from an earlier task to a later one. [3, 4, 1, 2, 0] is one. [4, 3, 2, 1, 0] is another. A graph often has several topological orders, and any of them is a correct answer.
To check an order, look up each task's position, then test every arrow. Line 2 of the trace builds that lookup with a dict comprehension: the list comprehension from module 1, written in curly braces with a key: value pair before the for. Here the key is a task and the value is its position, which enumerate supplies.
The trace runs the check on an order with a mistake in it, [3, 1, 0, 4, 2]. Before you step through, find the arrow that points backward.
def is_valid(order, arrows):position = {task: i for i, task in enumerate(order)}for before, after in arrows:if position[before] > position[after]:return Falsereturn True
(nothing printed yet)Four tasks have the arrows [[2, 0], [2, 3], [0, 1], [3, 1]], each written [before, after]. So task 2 goes before 0 and 3, and task 1 waits on both 0 and 3.
Which of these are topological orders? Pick every one that works.
Choose every option that applies, then check.
In-degree: what each task still waits for
Which task can go first? One that waits for nothing: no arrow points into it. The number of arrows pointing into a task is its in-degree. In the pipeline, report has in-degree 2 (arrows from 1 and 2), and the two loads have in-degree 0. A task with in-degree 0 is ready. We keep every task's in-degree in a list, in_degree, indexed by task number.
When a task finishes, the tasks waiting on it need to hear about it. So we keep a second list, dependents[t]: the tasks that wait on t, which are the tasks the arrows leaving t point to. This is the adjacency list from the first lesson of this module. The tasks are numbered from 0, so a list of lists does the dict's job: slot 3 holds the dependents of task 3. One pass over the arrows fills both lists: the arrow [before, after] adds after to dependents[before] and adds 1 to in_degree[after].
The trace builds both lists for the pipeline. Line 2 makes a separate empty list for each task, as in module 1 ([[]] * num_tasks would put one shared list in every slot). The arrows under each list show which slot the current pair touches. Before you step through, use the table to guess in_degree at the end.
def build(num_tasks, arrows):dependents = [[] for _ in range(num_tasks)]in_degree = [0] * num_tasksfor before, after in arrows:dependents[before].append(after)in_degree[after] += 1return dependents, in_degree
(nothing printed yet)This is the build loop on a new graph of four tasks. Type exactly what it prints, one list per line.
arrows = [[0, 2], [1, 2], [2, 3], [0, 3]]
dependents = [[] for _ in range(4)]
in_degree = [0] * 4
for before, after in arrows:
dependents[before].append(after)
in_degree[after] += 1
print(in_degree)
print(dependents)
Kahn's algorithm: release tasks as they become ready
What changes after a task runs? Every arrow out of it is now satisfied. So each of its dependents waits for one fewer task: lower its in-degree by 1. When that count reaches 0, the dependent has nothing left to wait for, and it becomes ready. From here on, in_degree[t] counts only the arrows into t from tasks that have not run yet: what t still waits for.
That is the whole algorithm, called Kahn's algorithm:
- Put every task with in-degree 0 into a queue of ready tasks.
- Take the task at the front of the queue and add it to the order.
- Lower the in-degree of each task that waits on it. Any that reach 0 join the back of the queue.
- Repeat until the queue is empty.
A queue, the notebook of breadth-first search from the last lesson, hands items out first in, first out, like a line at a counter. Any ready task would be safe to take next. The queue takes them in the order they became ready, which is what the problems and this widget do.
The widget runs these steps on the pipeline. Each task carries its in-degree as a number, and a count lowered on this step shows as before→after, such as 2→1. Under the graph are the ready queue and the order so far. Tasks 3 and 4 start ready. Before you press Next, guess which task becomes ready when task 3 runs.
Here is the same run in Python. Lines 4 to 8 are the build from the last section. Line 9 fills the queue with a generator expression (module 1: a comprehension inside a call, without its square brackets) that hands deque every task whose in-degree is 0, in number order. So the trace opens at step 37, with the lists built and the queue filled; press Back to watch the building.
A deque (a double-ended queue, from module 5) takes items off the front in O(1) with popleft(); list.pop(0) would shift every other item. The inner loop calls each waiting task nxt, short for next, because next is already the name of a Python built-in. Before you step through, guess how many times line 15 runs, and what in_degree holds when the call returns.
- order = []
from collections import dequedef topo_order(num_tasks, arrows):dependents = [[] for _ in range(num_tasks)]in_degree = [0] * num_tasksfor before, after in arrows:dependents[before].append(after)in_degree[after] += 1ready = deque(t for t in range(num_tasks) if in_degree[t] == 0)order = []while ready:task = ready.popleft()order.append(task)for nxt in dependents[task]:in_degree[nxt] -= 1if in_degree[nxt] == 0:ready.append(nxt)return order
5| 0 | 1 | |
|---|---|---|
| 0 | 3 | 1 |
| 1 | 1 | 0 |
| 2 | 3 | 2 |
| 3 | 2 | 0 |
| 4 | 4 | 2 |
[] (empty)(nothing printed yet)Here is the whole idea in the four questions:
The promise is why the order is right. A task joins the queue only when its count reaches 0, and the count only drops when a task it waits for is placed. So by the time a task is placed, everything it waits for is already in order.
The cost is why it is fast. V is the number of tasks and E the number of arrows (graph books say vertices and edges). Building the lists reads each arrow once. Each task joins the queue at most once (at the start, or the moment its count drops to 0), so each task is taken at most once, and taking a task walks only its own arrows. Over the whole run that is every task once and every arrow once more: O(V + E) time. The lists, the queue and the order hold O(V + E) items.
To recap: count the in-degrees, queue the tasks at 0, and each time you take a task, lower its dependents' counts and queue any that reach 0. Now assemble the loop yourself.
Put the lines in order to build release_all(ready, dependents, in_degree), the loop of Kahn's algorithm. ready arrives as a deque that already holds every task with in-degree 0. Add each task to order the moment it leaves the queue. Indentation is part of each line. Three lines do not belong.
Add lines from the list below, in order.
while ready:order.append(task)while order:in_degree[task] -= 1order = []ready.append(task)for nxt in dependents[task]:if in_degree[nxt] == 0:task = ready.popleft()def release_all(ready, dependents, in_degree):return orderin_degree[nxt] -= 1ready.append(nxt)
A graph has 6 tasks and 9 arrows and no cycle. Kahn's algorithm runs to the end. How many times does the line in_degree[nxt] -= 1 run in total?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
When the queue runs dry: cycles
What if no task is ready? Suppose someone makes orders read from report, to skip orders that were already reported. That adds the arrow [0, 3]: orders now waits on report, which waits on clean, which waits on orders. Tasks that wait on each other in a loop form a cycle, and no order can place every task of a cycle after the one before it.
Kahn's algorithm notices without any extra search. No task on a cycle can be the first of its cycle to come out: it waits on the task before it in the cycle, which would have to come out earlier. So the queue empties with tasks left over. Two lines check for it: if order is shorter than the number of tasks, return [].
The trace runs the same function on all six arrows, with those two lines added as lines 18 and 19. It opens at step 39, at the queue again. Before you step through, guess how many tasks make it into order.
- order = []
from collections import dequedef topo_order(num_tasks, arrows):dependents = [[] for _ in range(num_tasks)]in_degree = [0] * num_tasksfor before, after in arrows:dependents[before].append(after)in_degree[after] += 1ready = deque(t for t in range(num_tasks) if in_degree[t] == 0)order = []while ready:task = ready.popleft()order.append(task)for nxt in dependents[task]:in_degree[nxt] -= 1if in_degree[nxt] == 0:ready.append(nxt)if len(order) < num_tasks:return []return order
5| 0 | 1 | |
|---|---|---|
| 0 | 3 | 1 |
| 1 | 1 | 0 |
| 2 | 3 | 2 |
| 3 | 2 | 0 |
| 4 | 4 | 2 |
| 5 | 0 | 3 |
[] (empty)(nothing printed yet)Why do leftovers mean a cycle? By the promise, a task left out of order with a count of 0 would be in ready. So when the queue empties, every task left has in-degree at least 1, and each one waits on another task that is also left. Start at any of them and keep stepping to a task it waits on. There are only so many tasks, so the steps must come back to one already visited: a cycle. A task can also be stuck without being on the cycle, because it waits on a task that is.
Run Kahn's algorithm on paper for 6 tasks with the arrows [[0, 1], [1, 2], [2, 3], [3, 1], [0, 4], [3, 5]], each written [before, after]. Write in_degree, the queue and the order after each step, then reveal the steps to check. How many tasks come out?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Two problems, one algorithm
What changes when the tasks are courses? Course Schedule and Course Schedule II are this algorithm with courses as tasks. One detail changes, and it is worth reading twice: the pair order. Both problems write a prerequisite as [a, b], meaning course b must be finished before course a. That is [after, before], the reverse of our arrows, so the build loop reads:
for a, b in prerequisites:
dependents[b].append(a) # b comes first, so a waits on b
in_degree[a] += 1
A Course Schedule input: num_courses = 4, prerequisites = [[2, 0], [2, 1], [3, 2]]. Each pair [a, b] means course b must be finished before course a. After the build loop, what is in_degree?
Choose one answer, then check.
Course Schedule asks only yes or no: can every course be finished? You do not need the order itself. Count the courses you take, and compare the count with num_courses when the queue empties.
Two cases are worth saying out loud. A course that needs itself, [1, 1], has an in-degree only it could lower, so it never comes out. And two paths that meet again are not a cycle: if 3 needs 1 and 2, and both need 0, course 3 waits for two releases and comes out once, after both. A search that calls every second visit to a course a cycle gets that case wrong. Kahn's algorithm only counts, so it cannot.
Course Schedule II asks for the order, or [] when there is none. That is the function you traced, with the pair order flipped.
Return [] on a cycle, not the courses that came out before the queue ran dry: the problem asks for every course. When two courses are ready at the same time, either may go first, which is why the tests accept every valid order.
Interviewers reshape familiar problems, so practice the same algorithm in a new costume. Here the jobs have names, and each job lists the jobs it waits for, the way you would read them off an Airflow DAG.
Write run_order(upstream). upstream maps every job name to the list of jobs it waits for (an empty list when it waits for nothing). Every job named in a list is also a key, and no list names a job twice. Return a list of every job once, each after all the jobs it waits for, or [] if no such order exists. Any valid order passes.
The jobs have names, not numbers, so the notebook uses dicts instead of lists. Then press Watch it run on the lesson's pipeline.
raise NotImplementedError, then press Run tests. Each check says what it expects.The practice bank has one more costume, with no arrows at all: The best hub in a tree (LeetCode 310, Minimum Height Trees). Its links go both ways, so count each node's links instead of its in-degree, and peel off the nodes with one link left, round by round, until one or two remain.
Last, practice saying it. The words you write here are the words you will say in the room.
An interviewer gives you Course Schedule: can every course be finished? Explain your plan as you would before typing. Cover the walk, the notebook, the promise and the cost, and say how you will notice a cycle.
Saved in this browser as you type.