Topological sort: tasks with prerequisites
- Turn this-needs-that pairs into a graph with the arrows the right way round, from each prerequisite to the task that needs it
- Write Kahn's algorithm, which releases a task when its last prerequisite finishes, and say why it handles each task and each pair once, for O(V + E)
- Tell that there's a cycle because the order comes out short, name every task that can never run, and decide what to return
- Write the depth-first version with three states per task, and say what Python's recursion limit does to it on a long chain
- Get more than an order from the same loop, the fewest rounds and each task's earliest finish, and find which tasks can run late
- Answer the follow-ups, one fixed order among many, arrows hidden in a word list or a spreadsheet, a graph that changes and one too big for a machine
Order the tasks
Netflix software engineer candidates report topological sort in coding rounds, one of them as the phone screen (2 reports), and a senior candidate's version also asked when each task finishes (1 report). An Airbnb candidate reported a question about scheduling tasks in Airflow, a tool that runs pipelines of tasks that depend on each other (1 report). It starts like this:
You get a build pipeline.
tasksis a list of distinct task names.needsis a list of(task, prerequisite)pairs, and each pair meanstaskcan't start untilprerequisitehas finished. Every name in a pair is intasks. A task can be in no pair at all, and the same pair can be listed twice.Write
build_order(tasks, needs). Return a list that holds every task exactly once, each one after all of its prerequisites. When several orders work, any of them passes. For now, every pipeline can run to the end.These calls show one valid answer each:
build_order(["test", "build"], [("test", "build")])returns["build", "test"]build_order(["deploy", "test", "build"], [("deploy", "test"), ("test", "build")])returns["build", "test", "deploy"]build_order(["deploy", "lint", "test"], [("deploy", "lint"), ("deploy", "test")])returns["lint", "test", "deploy"]build_order(["docs", "build"], [])returns["docs", "build"]build_order(["test", "build"], [("test", "build"), ("test", "build")])returns["build", "test"]build_order([], [])returns[]
Two more levels follow. Level 2 puts mistakes in the pipeline, such as two tasks that need each other: build_order raises ValueError when any task can never run, and a new stuck_tasks returns every such task, sorted. Level 3 gives each task a number of minutes, with as many workers as tasks, and asks when each task finishes and when the whole pipeline is done.
You don't write it yet. The lesson first turns the pairs into a graph, then builds the loop that releases a task when its last prerequisite finishes. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.
This lesson builds on the grid search: Kahn's algorithm is a breadth-first search over tasks instead of cells, with each task's count of open prerequisites in a dict. Ordering work by what it depends on comes back in the work queue, in the coding builds.
Prerequisites are a directed graph
Every question in this lesson hands you tasks, and pairs that say one task can't start until another has finished. Courses and the courses they require. Build steps. Spreadsheet cells and the cells their formulas read.
Each pair is an arrow from the prerequisite to the task that needs it
tasks = ["fetch", "compile", "assets", "test", "package", "docs", "deploy"]
needs = [
# compile needs fetch
("compile", "fetch"),
("assets", "fetch"),
("test", "compile"),
("package", "compile"),
("package", "assets"),
("deploy", "test"),
("deploy", "package"),
]
for task, prerequisite in needs:
print(f"{prerequisite} -> {task}")
fetch -> compile
fetch -> assets
compile -> test
compile -> package
assets -> package
test -> deploy
package -> deploy
Each pair is (task, prerequisite). The arrow runs the other way, from the prerequisite to the task that needs it, because that's the order things happen in: fetch finishes, and then compile can start. Drawn out, the pipeline looks like this:
docs is in no pair. It needs nothing, and nothing needs it.
This is a directed graph: the tasks are its nodes, and each pair is an edge, an arrow with a direction. On a grid, an edge went both ways. Here compile needs fetch, and fetch doesn't need compile.
The editor holds the pipeline's needs. Write arrows, which turns each pair into its arrow, and needed_by, which lists the tasks that a finished task releases.
An order is valid when every arrow points forward, and most graphs have many
With the graph drawn, the question is what a valid order looks like.
How many valid orders does the 7-task pipeline have?
Two dicts hold the graph: what each task unblocks, and how many prerequisites it waits for
To run the tasks, the code needs the graph in a form it can walk quickly.
from collections import defaultdict
def build_graph(tasks, needs):
unblocks = defaultdict(list)
# every task, even one in no pair
waiting = dict.fromkeys(tasks, 0)
for task, prerequisite in needs:
# the arrow: prerequisite -> task
unblocks[prerequisite].append(task)
waiting[task] += 1
return unblocks, waiting
unblocks, waiting = build_graph(tasks, needs)
for task in tasks:
print(f"{task:8} unblocks {unblocks[task]}, waits for {waiting[task]}")
build_graph runs on the pipeline. Which tasks get a count of 0?
Start from the task list, so a task in no pair still gets a count of 0
A task that's in no pair is easy to lose. docs is the one in the pipeline:
from_pairs = {name for pair in needs for name in pair}
print(sorted(set(tasks) - from_pairs))
print(waiting["docs"], unblocks["docs"])
['docs']
0 []
dict.fromkeys(tasks, 0) gives every task a count of 0 before the loop, docs included.
unblocks is a defaultdict(list), so unblocks["docs"] reads as []. That read adds the key, the trap from the hash-maps lesson. Here it's harmless.
The editor holds graph_from_config(config), for a CI config that maps each task to the tasks it needs. Fill in its loop so it returns unblocks and waiting with a key for every task.
A CI config maps each task to the tasks it needs: {"test": ["build"], "build": ["fetch"]}. A task that needs nothing may be left out of the keys and named only in another task's list, like fetch here. Finish graph_from_config(config): return (unblocks, waiting), two dicts with a key for every task, where unblocks[t] lists the tasks that need t and waiting[t] counts the prerequisites of t.
William Fiset on what a topological order is, why it needs a graph with no cycles, and what goes wrong when there is one.
Sorting by the count can break the order, and rescanning for a ready task is slow
Two first ideas are tempting, and neither is the answer.
Sorting by the count can put a task before what it needs
Sorted by count: compile, assets, release, package. release lands before package, which it needs.
sorted(tasks, key=waiting.get) puts the tasks that need nothing first, and on the pipeline it happens to give a valid order. On these four it doesn't. A count says how many prerequisites a task has, not how long the chain behind them is.
Rescanning for a ready task works, but a chain listed backwards takes n(n + 1)/2 checks
def rescan_order(tasks, needs):
prerequisites = defaultdict(list)
for task, prerequisite in needs:
prerequisites[task].append(prerequisite)
done, order, remaining = set(), [], list(tasks)
while remaining:
for task in remaining:
if all(p in done for p in prerequisites[task]):
break
else:
raise ValueError("no task can run")
remaining.remove(task)
done.add(task)
order.append(task)
return order
This finds any task whose prerequisites have all run, places it, and looks again. The else belongs to the for: it runs only when the loop ends without a break, here when no task is ready. It's correct. It's also slow, because it forgets everything between passes. Its worst case is a chain listed backwards:
10 checks in all, to place 4 tasks.
Every pass walks to the end of what's left to find the one ready task. For tasks that's checks, times over 2. It came to 500,500 checks for 1,000 tasks, and 32,004,000 for 8,000.
The editor holds the pipeline and an empty ready_now. Write it to return the tasks the rescan could place next, given the set of tasks already done.
Kahn's algorithm queues a task the moment its count reaches 0
The rescan finds each ready task by searching again. Kahn's algorithm never searches: it notices the moment a task becomes ready. Kahn's algorithm keeps the answer up to date instead of working it out again each time:
- Count every task's prerequisites.
build_graphandgraph_from_configalready do. - Queue every task whose count is 0. The queue is a
collections.deque, so taking the oldest task withpopleft()is . - Take the oldest task off the queue and put it in the order. Take one off the count of every task it unblocks. A task whose count reaches 0 goes on the queue.
- Repeat until the queue is empty. The order is the answer.
Kahn's pops compile before assets. Right after compile is popped, what is package's count?
Each task is popped once and each pair handled once, so Kahn's is O(V + E)
Here is what that change is worth, timed on chains of tasks.
| Tasks in the chain | Rescan | Kahn's |
|---|---|---|
| 1,000 | 144.8 ms | 0.30 ms |
| 2,000 | 611.2 ms | 0.61 ms |
| 4,000 | 2,402.0 ms | 1.31 ms |
| 8,000 | 9,987.5 ms | 2.52 ms |
Each task goes on the queue once and comes off once. Each pair is handled once, when its prerequisite is popped and its task's count drops by one. On the chain of 8,000 that's 8,000 pops and 7,999 decrements, against the rescan's 32 million checks.
The times are from Python 3.12 on one laptop, best of 3 runs for the rescan and of 5 for Kahn's. Double the tasks and the rescan takes four times as long, , while Kahn's takes twice as long.
The editor holds Kahn's loop as kahn_work, with two counters that never move. Make pops and decrements count, and compare the totals with V and E.
Any ready task can go next, so one graph can give several valid orders
When several tasks are ready at once, which one goes first?
Pop the newest ready task instead, from a stack. Which task comes first?
Cycles: the order comes out short
Every graph so far had no cycle. Add one, and run your order_from_config on it.
A cycle stops Kahn's loop early, and the tasks on it never reach 0
# compile now needs test too
broken = needs + [("compile", "test")]
config = {task: [p for t, p in broken if t == task] for task in tasks}
order = order_from_config(config)
print(order)
print(len(order), "of", len(tasks), "tasks")
One pair is added: compile now needs test too. How many tasks make it into Kahn's order?
Kahn's runs on the tasks lint and format, with the one pair ("lint", "lint"). What does it return?
Ask what to return, because a graph with a cycle has no full order
A cycle means no full order exists, so the function has to return something else. Python's own graphlib makes one choice.
from graphlib import CycleError, TopologicalSorter
graph = {task: [] for task in tasks}
for task, prerequisite in broken:
graph[task].append(prerequisite)
try:
list(TopologicalSorter(graph).static_order())
except CycleError as error:
print(error.args)
Python's own sorter raises CycleError on the broken pipeline. Which tasks does its message name?
The depth-first version
Kahn's algorithm is one way to order the tasks. A depth-first search gives an order too, read off the moment each task finishes.
With no cycle, the depth-first finish order, reversed, is a build order
NEW, ACTIVE, DONE = 0, 1, 2
def dfs_order(tasks, needs):
unblocks, _ = build_graph(tasks, needs)
state = dict.fromkeys(tasks, NEW)
finished = []
def visit(task):
state[task] = ACTIVE
for nxt in unblocks[task]:
if state[nxt] == ACTIVE:
raise ValueError(f"cycle through {nxt}")
if state[nxt] == NEW:
visit(nxt)
state[task] = DONE
finished.append(task)
for task in tasks:
if state[task] == NEW:
visit(task)
return finished[::-1]
print(dfs_order(tasks, needs))
dfs_order starts at fetch and follows unblocks as deep as it goes. Which task finishes first?
Only an ACTIVE task means a cycle, so the search needs three states
Run the depth-first version on the broken pipeline, the one with a cycle.
try:
dfs_order(tasks, broken)
except ValueError as error:
print("ValueError:", error)
dfs_order runs on the broken pipeline, where compile also needs test. Which task does the error name?
On a long chain the recursion can pass Python's default limit of 1,000 frames
The depth-first version is recursive, and on a long chain that matters.
Listed first task first, each visit calls the next before it finishes. Listed last task first, each visit finds the next task DONE already.
That depth is the catch in Python: the default recursion limit is 1,000 frames, as in the grid lesson.
From a script, a chain of 998 tasks worked, and 999 raised RecursionError: maximum recursion depth exceeded. The other two frames went to the script itself and the call to dfs_order. Listed last task first, the same chain went through.
You don't choose how inputs arrive, so plan for the deep case. sys.setrecursionlimit(200_000) let a chain of 100,000 tasks through, but the docs warn that a limit set too high can lead to a crash. Kahn's keeps its pending work in a deque, and has no depth at all.
The editor holds deepest_call and a chain of 5 tasks. Finish its visit so it records how many calls are open at the deepest point.
Walk the needs arrows instead, and the finish order needs no reversal
The reversal comes from the direction you walk. Follow the needs arrows instead, from a task to its prerequisites. Then a task finishes after all of its prerequisites have, so the finish order is already a build order.
Follow the needs arrows instead, starting at deploy. Which task finishes first?
More than an order: rounds and finish times
Some questions ask for more than an order: how many rounds the tasks take with enough workers, or when each one finishes.
With one-minute tasks and enough workers, the fewest rounds is the longest chain
from collections import deque
def count_rounds(tasks, needs):
unblocks, waiting = build_graph(tasks, needs)
queue = deque(task for task in tasks if waiting[task] == 0)
rounds = ran = 0
while queue:
rounds += 1
# exactly this round's tasks
for _ in range(len(queue)):
task = queue.popleft()
ran += 1
for nxt in unblocks[task]:
waiting[nxt] -= 1
if waiting[nxt] == 0:
# waits for the next round
queue.append(nxt)
return rounds if ran == len(tasks) else -1
print(count_rounds(tasks, needs), count_rounds(tasks, broken))
4 -1
Say every task takes one minute, and as many run at once as are ready.
Netflix's LeetCode tag list includes Parallel Courses (1 source), tagged Topological Sort, and this is its shape.
The fewest rounds is the grid lesson's one level per pass, with Kahn's counts in place of the seen-set.
With one-minute tasks and as many workers as you like, which round does package run in?
With enough workers, a task starts when its last prerequisite finishes, or at 0 if it has none
So far every task took one minute.
minutes = {"fetch": 2, "compile": 5, "assets": 3, "test": 8, "package": 2, "docs": 4, "deploy": 1}
Now give the tasks real durations, still with as many workers as you need. A senior Netflix candidate reported a version of this: topological sort with the extra work of tracking when each prerequisite finishes (1 report).
A task starts when its last prerequisite finishes, or at 0 if it has none, and it finishes minutes[task] later:
Here is a task and runs over its prerequisites. The max is 0 for a task with no prerequisites.
With as many workers as you like, at what minute is the whole pipeline done?
With enough workers, the done time is the longest chain in minutes, and one pass finds it
The pipeline is done at 16, the largest finish, where one worker would take 25. 16 is the longest chain measured in minutes, and that chain is the critical path, the chain that sets the done time.
The booksite's critical path method schedules jobs that must wait for other jobs the same way: each job starts at the length of its longest path from the start.
The obvious way to get a longest chain is to list every chain of prerequisites that ends at a task, and keep the longest. The number of chains can double with every step. Take a ladder: stages of two tasks, each task needing both tasks of the stage before, each one minute.
def ladder(stages):
tasks = [f"{side}{i}" for i in range(stages) for side in "ab"]
needs = [(f"{x}{i + 1}", f"{y}{i}") for i in range(stages - 1) for x in "ab" for y in "ab"]
return tasks, needs
def finish_by_chains(tasks, needs, minutes):
prerequisites = defaultdict(list)
for task, prerequisite in needs:
prerequisites[task].append(prerequisite)
def longest(task):
return minutes[task] + max((longest(p) for p in prerequisites[task]), default=0)
return {task: longest(task) for task in tasks}
Here is a ladder of 4 stages:
How many chains of prerequisites end at a3, counting a3 alone?
A worked example: which tasks can run late
The problem: the pipeline above, with its minutes. For every task, how many minutes can it finish late without moving the minute the whole pipeline is done? That number is the task's slack. A task with no slack is on the critical path.
Say the rules back, then cost the obvious answer
1. Clarify. Say it out loud:
- As many workers as needed, and whole minutes.
- A cycle is an error.
- A task that finishes late pushes everything downstream of it.
- Slack is measured on the finish time.
- The output is a dict from each task to its slack.
2. The obvious answer. Delay one task by a minute, work out every finish time again, and see whether the done time moves.
Delay each of the V tasks in turn, and redo every finish time each time. What does that cost in all?
Walk the order backwards to get each task's latest finish
3. The insight. Run the same idea backwards. The forward pass gives each task's earliest finish and the done time. Then walk the order in reverse:
- A task that nothing needs can finish as late as the done time.
- Any other task must finish before each task that needs it has to start. The latest a task can start is its own latest finish minus its minutes.
- So a task's latest finish is the smallest of those, and its slack is its latest finish minus its earliest.
def slack(tasks, needs, minutes):
finish = earliest_finish(tasks, needs, minutes)
done = max(finish.values(), default=0)
unblocks, _ = build_graph(tasks, needs)
latest = {}
# every dependent comes first
for task in reversed(kahn_order(tasks, needs)):
latest[task] = min((latest[nxt] - minutes[nxt] for nxt in unblocks[task]), default=done)
return {task: latest[task] - finish[task] for task in tasks}
earliest_finish is the forward pass from the checkpoint above. Reversing the order puts every task after the tasks that need it, so their latest finishes are final when it reads them. It's the forward pass with the arrows turned around, and max turned into min.
The editor holds a latest_finish with one bug, and the pipeline's minutes. Find the bug and fix it.
The tasks with no slack are the critical path
4. Trace it on the pipeline, in reverse order.
Walk backwards from deploy, which must finish by 16. What is compile's latest finish?
Slow each task down to test the slack, then give the cost
5. Test it the way you'd convince an interviewer: rerun the forward pass with one task slowed down.
package has 6 minutes of slack. Slow it down by 7. When is the pipeline done?
What interviewers ask next
Need one fixed order? Keep the ready tasks in a heap, for O(E + V log V)
Kahn's leaves the choice of ready task open, and a problem statement may close it: smallest name first, say. Keep the ready tasks in a heap instead of a deque, so each pop takes the smallest.
The ready tasks go in a heap, smallest name first. Which task comes third?
Alien Dictionary? The arrows hide in a sorted word list
A famous follow-up hides the graph: all you get is a list of words in an alien language, sorted by its alphabet.
In a list sorted in an unknown alphabet, kite comes right before kin. What does that pair tell you?
A spreadsheet? Recompute only the cells downstream of a change
Design Excel Sum Formula is on OpenAI's and Airbnb's LeetCode tag lists (3 sources), with Topological Sort among its tags. A cell whose formula reads other cells needs them, so each reference is a pair.
A1 holds 5 and A2 holds 7. B1 is = A1 * 2, C1 is = B1 + A1, B2 is = A2 + 1, and C2 is = B1 + B2. A1 changes. Which cells need working out again?
Which new pair closes a cycle in the pipeline?
Only two workers? Now the order of ready tasks matters
With unlimited workers, the order of ready tasks never mattered. With two it does. Take four 3-minute tasks a, b, c and d, where d needs a.
Two workers start b and c first. When is everything done?
Kahn's runs in rounds on 100 machines. Double the machines. What happens to the number of rounds?
What tests would you write? A checker first, then the edge cases
Write a checker rather than one expected list: every task once, and every pair pointing forward. Then the inputs:
- no tasks, one task, and tasks in no pair
- a repeated pair
- a chain listed backwards
- a task whose prerequisites sit at different depths
- a cycle with nothing ready, a cycle behind tasks that can run, and a task that needs itself
- a zero-minute task, and a done time that isn't the last task's
- a chain thousands long, listed in both directions, to catch the recursion limit
The editor holds the pipeline and the order that put deploy before package. Write problems, which names each task that is wrong in an order.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.In Kahn's algorithm, when does a task go on the queue?
2.Kahn's algorithm stops with 3 of 7 tasks in the order. What do you know about the other 4?
3.A pipeline has V tasks and E pairs. What does Kahn's algorithm cost, and what does rescanning the list for a ready task cost at worst?
4.Your depth-first sort keeps one seen-set and raises a cycle error whenever it reaches a task already in it. What happens on a pipeline where deploy needs both test and package, and both need compile?
5.package takes 2 minutes and needs compile, which finishes at minute 7, and assets, which finishes at minute 5. Kahn's pops compile first, then assets. With as many workers as you like, when does package finish?
6.You run the lesson's
dfs_order, which followsunblocks, on a chain of 5,000 tasks, each needing the one before and listed first task first, with Python's default settings. What happens?
Practice
Sources (6)
- graphlib: TopologicalSorter · Python 3.12 documentation · Oct 26, 2026
“A complete topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph.”
- graphlib: CycleError · Python 3.12 documentation · Oct 26, 2026
“If multiple cycles exist, only one undefined choice among them will be reported and included in the exception.”
- 4.2 Directed Graphs · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jan 14, 2020
“Reverse postorder in a DAG is a topological sort.”
- 4.4 Shortest Paths: critical path method · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jan 10, 2025
“Now, schedule each job at the time given by the length of its longest path from the source.”
- sys.setrecursionlimit · Python 3.12 documentation · Oct 26, 2026
“This should be done with care, because a too-high limit can lead to a crash.”
- heapq: Heap queue algorithm · Python 3.12 documentation · Oct 26, 2026
“The interesting property of a heap is that its smallest element is always the root, heap[0].”