Topological sort: line up what has to come first
Which module do you compile first? Which course do you take first? When rules like "finish this before that" are tangled together, you need an order. Press "Next" and build the line one step at a time.
Short answer. A topological sort takes a graph whose arrows mean "this has to come first" and lines up its nodes so that every arrow points from earlier to later. The easy way: put the nodes with no incoming arrows (tasks with nothing before them) into a queue, take them out one by one, put each in line, and remove the arrows going out of it. If the arrows form a cycle, no such line exists. It takes time in proportion to the number of nodes plus the number of arrows.
Taking one node out is split into three steps: take it out of the queue and put it in the order → remove its outgoing arrows and lower in-degrees → put nodes that reached 0 into the queue. The number at the top right of a box is how many incoming arrows it still has (its in-degree); on a step that lowers it, it shows the old and new value, like "2 → 1". The label under a box: "#3" is its place in the order, "queue 1" is its place in the queue (1 comes out next), "stuck" means it could never be placed. A small arrow above a box points at the node taken out ("taken out") or put into the queue ("into queue") on this step. Orange is the node being handled and the arrows being removed now (dashed). Green nodes are in the order. Blue dashed nodes wait in the queue. Red marks nodes that could never be placed and the thick arrows that form the cycle ("cycle"). Faded arrows are already removed. Pressing "Add a backward arrow" goes back to the first step.
Definitions
The text below explains in plain words. These are the textbook definitions. V is the set of nodes and E is the set of edges (arrows). When we write running time, V and E also stand for how many there are (the O(V + E) in the text).
- directed graph
- A graph G = (V, E) whose edges are ordered pairs (u, v) of nodes. The edge (u, v) leaves u and enters v, and is written u → v.
- DAG (directed acyclic graph)
- A directed graph with no directed cycle. A directed cycle is a path that follows the edges in their direction through one or more edges and comes back to the node it started from.
- in-degree
- The number of edges that enter a node v. A node with in-degree 0 is called a source.
- topological sort
- Putting the nodes of a directed graph in one line so that for every edge (u, v), u comes before v. The line you get is a topological order. If π(v) is the place of node v in the line, the condition is below. A topological order exists if and only if the graph is a DAG.
- Kahn's algorithm
- A topological sort method. Put every node with in-degree 0 in a queue. Then repeat until the queue is empty: take a node u from the queue and put it at the end of the line, and for each edge (u, v) leaving u, lower the in-degree of v by 1 and put v in the queue when it reaches 0. If fewer than V nodes end up in the line, the graph has a directed cycle. It takes O(V + E) time.
- postorder
- In depth-first search, the order in which nodes are written down when they finish, that is, after every edge leaving the node has been followed. In a DAG, the reverse of the postorder (reverse postorder) is a topological order.
1. Graphs with arrows, and lining them up
The nodes in the graph above are 8 modules of a made-up program. An arrow X → Y means "X must be built before Y can be built", that is, Y uses X. In graph search the edges went both ways. Here every edge has a direction. A graph like this is called a directed graph.
A topological sort lines the nodes up so that every arrow goes from a node earlier in the line to a node later in the line. Build in this order, and whenever you build a module, every module it uses is already built.
If you can follow arrows and come back to where you started, there is a cycle, and no such line exists. Each node on the cycle must stand after the node before it on the cycle, so after one lap a node would have to stand after itself. A directed graph with no cycle is called a DAG, and a topological order exists if and only if the graph is a DAG (source ①).
In Python, store it as a dict that lists, for each node, the nodes that must come after it (where its arrows go). There are 9 arrows.
after = {"config": ["db"], "utils": ["db", "ui"], "db": ["auth", "api"], "auth": ["api"],
"api": ["app"], "ui": ["app"], "app": ["test"], "test": []}
2. The queue method: start with what waits for nothing
For each node, count its incoming arrows. Books call this the in-degree. It means "how many things still have to finish before this one".
- Put every node with in-degree 0 into the queue. Nothing has to come before them.
- Take one node out of the queue and put it at the end of the line.
- Remove the arrows going out of it. That is, lower the in-degree of each node those arrows point to by 1, and put any node that reaches 0 into the queue.
- Repeat 2 and 3 until the queue is empty.
A node you take out has in-degree 0, so every node that must come before it is already in line. Putting it at the end of the line never makes an arrow point backward.
Try this. ① At the start the queue holds config and utils. They are the only nodes with no incoming arrows. ② Press "Next" 20 times and the order is config, utils, db, ui, auth, api, app, test. That is 8 steps that take a node out, 7 that remove arrows (test has no arrows out) and 5 that put nodes into the queue. All 9 arrows in the picture point forward in this order. ③ Step 6 takes out db and step 7 removes its arrows: auth drops to 0, but api stays at 1. api is also waiting for auth. So at step 8 only auth goes into the queue. ④ The queue is at most 2 long (at the start, step 5 and step 8).
3. Follow it by hand
This is the same graph as the demo. The starting in-degrees are config 0, utils 0, db 2, auth 1, api 2, ui 1, app 2, test 1. Each row is one round, and each round takes one node out of the queue. The demo splits a round into three steps: take out, remove arrows, put into the queue (a step is skipped when there are no arrows to remove or no node reaches 0). The left end of the queue is the front (what comes out next).
| Round | Node taken out | In-degrees lowered (new value) | Queue after | Order so far | Why |
|---|---|---|---|---|---|
| 0 | (start) | – | config utils | (none) | They are the only nodes with no incoming arrows |
| 1 | config | db 1 | utils | config | db also waits for utils |
| 2 | utils | db 0, ui 0 | db ui | config utils | Everything db and ui waited for is now in line |
| 3 | db | auth 0, api 1 | ui auth | config utils db | auth waited only for db; api also waits for auth |
| 4 | ui | app 1 | auth | config utils db ui | app also waits for api |
| 5 | auth | api 0 | api | config utils db ui auth | Both db and auth, which api waited for, are in line |
| 6 | api | app 0 | app | config utils db ui auth api | Both ui and api, which app waited for, are in line |
| 7 | app | test 0 | test | config utils db ui auth api app | test waited only for app |
| 8 | test | (no arrows out) | (empty) | config utils db ui auth api app test | The queue is empty, so it ends |
Look at round 4. Taking out ui lowers app to 1, but app is still waiting for api. app only enters the queue in round 6, after api comes out.
4. With a cycle, you cannot finish
Press "Add a backward arrow" in the demo to add the arrow auth → config. Now config uses auth. That makes config → db → auth → config a cycle. Each of the three waits for the one before it on the cycle, so none of them can ever enter the queue first.
Try this. ① With the arrow on, the queue starts with utils alone. config now has one incoming arrow, so its in-degree is 1. ② Press "Next" five times: utils and ui go in line and it ends with the queue empty. ③ Six nodes are left: config, db, auth, api, app, test. Only config, db and auth are on the cycle. api, app and test come after the cycle, so they are stuck too.
So the queue method doubles as a cycle check. If the queue is empty and fewer nodes are in line than there are in the graph, there is a cycle. But not every left-over node is on the cycle.
5. With depth-first search: reverse the finishing order
Depth-first search can also line the nodes up. Walk only along the arrows, and write a node down after you have followed every arrow out of it to the end (when the node is "finished"). In a graph with no cycle, reversing this finishing order gives a topological order (source ①).
Here is why. With no cycle, if there is an arrow X → Y, Y finishes before X. If Y was already visited, it has already finished. If not, the search goes into Y and finishes it before X can finish. So once you reverse the finishing order, X stands before Y.
def topo_dfs(after):
done, finished = set(), []
def visit(node):
done.add(node)
for next_node in after[node]:
if next_node not in done:
visit(next_node)
finished.append(node) # write it down after following every arrow out of it
for node in after:
if node not in done:
visit(node)
return finished[::-1]
print(topo_dfs(after)) # ['utils', 'ui', 'config', 'db', 'auth', 'api', 'app', 'test']
The order differs from the queue method, but it also keeps all 9 arrows. This code does not check for cycles. With a cycle there is no topological order, so whatever it returns has an arrow pointing backward. You have to check for a cycle separately.
6. Time
time ∝ V + E (in book notation: O(V + E))
V: the number of nodes. In the queue method each node goes into the queue once and comes out once.E: the number of arrows. Each arrow is looked at once when counting in-degrees and once when lowering them.∝: is proportional to. Double the nodes and the arrows and the time roughly doubles.O( ): notation that keeps only how fast the time grows as the input grows (time complexity).
The depth-first method also enters each node once and follows each arrow once, so it is also proportional to V + E (source ①). The graph above has V = 8 and E = 9.
7. When to use which
| Method | Time (best · typical · worst) | Extra memory | Good | Bad | Use it when |
|---|---|---|---|---|---|
| Queue method (in-degrees) | V + E · V + E · V + E. It always looks at every node and arrow once (double both and it doubles) | V in-degree slots + the queue (at most V) | No recursion. Left-over nodes reveal a cycle as soon as the queue empties. Nodes in the queue at the same time never wait for each other | You have to count in-degrees first | The input might have a cycle, or you need a cycle check along with the order |
| Depth-first (reverse finishing order) | Same | V visited marks + V for the finishing list + recursion depth (at most V) | Add one line ("write it down when finished") to a depth-first search | Needs a separate cycle check. With recursion, a very long chain of arrows can make the calls too deep | You know there is no cycle, or you already have a depth-first search |
If you would rather not write it yourself, use graphlib from the Python standard library (section 8).
8. In Python
from collections import Counter, deque
def topo_queue(after):
indegree = Counter(node for targets in after.values() for node in targets) # incoming arrows per node
queue, order = deque(node for node in after if indegree[node] == 0), []
while queue:
node = queue.popleft()
order.append(node)
for next_node in after[node]:
indegree[next_node] -= 1
if indegree[next_node] == 0:
queue.append(next_node)
return order # shorter than the node count means there is a cycle
print(topo_queue(after)) # ['config', 'utils', 'db', 'ui', 'auth', 'api', 'app', 'test']
after is the dict from section 1. The standard library has this too (since Python 3.9).
from graphlib import TopologicalSorter
before = {node: [m for m in after if node in after[m]] for node in after} # nodes that must come before each node
print(list(TopologicalSorter(before).static_order())) # ['config', 'utils', 'db', 'ui', 'auth', 'api', 'app', 'test']
TopologicalSorter takes the arrows the other way round. The keys of the dict are nodes, and each value is the nodes that must come before that node. static_order() gives the nodes in a topological order, and the order can depend on the order things were added. With a cycle it raises CycleError (a subclass of ValueError) (source ②).
Where it is used
- Course prerequisites. Write "take A before B" as arrows, and a topological order is an order in which you can take the courses.
- The order to compile parts of a program. When one part uses another, compile the user later. The demo is a made-up case of this. If parts use each other in a cycle, no order is possible.
Questions
Is there only one topological order?
No. On this page's graph the queue method gives config, utils, db, ui, auth, api, app, test and the depth-first method gives utils, ui, config, db, auth, api, app, test. Both keep every arrow. The Python graphlib documentation also says the order can depend on the order things were added.
How do I know there is a cycle?
In the queue method, if the queue is empty and some nodes are still not in line, there is a cycle. graphlib's TopologicalSorter raises CycleError. Not every left-over node is on the cycle. Nodes that come after the cycle are stuck too.
Is this the same as breadth-first search?
Both use a queue, but they put nodes in at different times. Breadth-first search puts a neighbor in as soon as it sees it. The queue method of topological sort puts a node in only when all its incoming arrows are gone and its in-degree is 0. So it starts from every node with in-degree 0, not from one start node.
Words
| Word on this page | Also called |
|---|---|
| node | vertex |
| arrow | directed edge |
| graph with arrows | directed graph, digraph |
| cycle | directed cycle |
| graph with arrows and no cycle | DAG, directed acyclic graph |
| number of incoming arrows | in-degree |
| node with no incoming arrows | source |
| lining up | topological sort |
| the line | topological order |
| queue method | Kahn's algorithm |
| finishing order | postorder |
| finishing order reversed | reverse postorder |
Sources
- Robert Sedgewick, Kevin Wayne, Algorithms, 4th ed., 4.2 Directed Graphs. Topological sort and DAGs, when a topological order exists, reverse postorder and its V + E time, the non-recursive method with in-degrees and a queue (exercise), course prerequisites and compile order.
- Python documentation: graphlib. The shape of the dict TopologicalSorter takes, static_order, CycleError.