Sub topic 11
Topological Sorting from Finish Order
This chapter assumes you can already write recursive DFS, track discovery and finish times, and tell a back edge from the other edge types. It also uses the three-color cycle detection from the previous chapter. With those pieces, a topological sort takes one extra line of code.
What a Topological Order Is
A topological order of a directed graph lists every vertex so that for each edge u -> v, u comes before v. Read an edge as "u must happen before v". The order is then a schedule that respects every constraint.
Common uses:
- Build systems that compile a module after the modules it imports.
- Package managers that install dependencies before the packages that need them.
- Spreadsheets that recompute a cell after the cells its formula reads.
- Course planners that place prerequisites before the courses that need them.
A topological order exists only when the graph is a directed acyclic graph (DAG), meaning a directed graph with no cycles. If a -> b -> a, then a must come before b and b must come before a, which is impossible.
A DAG usually has more than one valid order. Any order that satisfies every edge is correct. Tests should check that property and should not compare against one fixed list.
The Key Fact: Edges Point Toward Earlier Finishers
Run DFS over the whole graph and record when each vertex finishes. In a DAG, every edge u -> v satisfies:
finish(v) < finish(u)
Here is why. When DFS is at u and looks at the edge u -> v, vertex v is in one of three states:
| State of `v` | What happens | Result |
|---|---|---|
| White (undiscovered) | DFS descends into `v` as a tree edge. `v` finishes before control returns to `u`. | finish(v) < finish(u) |
| Black (finished) | `v` already has its finish time. `u` is still open. | finish(v) < finish(u) |
| Gray (on the current path) | The edge is a back edge, so the graph has a cycle. | Cannot happen in a DAG |
The case the argument rules out is exactly the case cycle detection looks for. So "no back edges" and "finish order reversed is a topological order" are two consequences of the same fact.
If you list vertices by decreasing finish time, every edge points from a later finisher to an earlier finisher, which means from left to right. You don't need timestamps for this. Append each vertex to a list when it finishes (post-order), then reverse the list.
The Algorithm
def topological_sort(graph):
visited = set()
postorder = []
def visit(node):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
postorder.append(node) # appended when the node finishes
for node in graph:
if node not in visited:
visit(node)
return postorder[::-1]
deps = {
"shirt": ["tie"],
"tie": ["jacket"],
"pants": ["shoes", "jacket"],
"shoes": [],
"jacket": [],
}
print(topological_sort(deps)) # ['pants', 'shoes', 'shirt', 'tie', 'jacket']The outer loop matters. One DFS from a single start vertex reaches only what that vertex can reach. Looping over all vertices builds the full DFS forest, so every vertex gets a finish time.
Tracing the Finish Order
| Step | Event | postorder so far |
|---|---|---|
| 1 | Discover shirt, then tie, then jacket | [] |
| 2 | jacket finishes (no out-edges) | [jacket] |
| 3 | tie finishes | [jacket, tie] |
| 4 | shirt finishes | [jacket, tie, shirt] |
| 5 | Outer loop: tie is visited. Discover pants, then shoes | [jacket, tie, shirt] |
| 6 | shoes finishes | [jacket, tie, shirt, shoes] |
| 7 | pants skips jacket (black) and finishes | [jacket, tie, shirt, shoes, pants] |
Reversing gives pants, shoes, shirt, tie, jacket. Check every edge: pants comes before shoes and jacket, shirt before tie, and tie before jacket. Step 7 is the black case from the table. The edge pants -> jacket is a cross edge, and jacket finished long before pants.
Common Error: Using Discovery Order
Pre-order (the order vertices are discovered) looks plausible but is wrong. Take {"a": ["b", "c"], "c": ["b"]}. DFS from a discovers a, then b, then c. The edge c -> b needs c before b, and pre-order puts b first. Post-order is b, c, a, and its reverse a, c, b is correct. A vertex counts as "done" only when everything it points to is done, and that moment is its finish.
Making It Safe: Reject Cycles
The plain version above never complains. Given a cyclic graph, it silently returns an order that breaks at least one edge. Real dependency tools have to report the cycle. Switching to three colors finds it at no extra cost:
WHITE, GRAY, BLACK = 0, 1, 2
def topo_sort_checked(graph):
color = {node: WHITE for node in graph}
postorder = []
def visit(node):
color[node] = GRAY
for neighbor in graph[node]:
if color[neighbor] == GRAY:
raise ValueError(f"cycle detected via edge {node} -> {neighbor}")
if color[neighbor] == WHITE:
visit(neighbor)
color[node] = BLACK
postorder.append(node)
for node in graph:
if color[node] == WHITE:
visit(node)
return postorder[::-1]
def is_topological(graph, order):
position = {node: i for i, node in enumerate(order)}
return all(position[u] < position[v] for u in graph for v in graph[u])
deps = {"shirt": ["tie"], "tie": ["jacket"], "pants": ["shoes", "jacket"],
"shoes": [], "jacket": []}
order = topo_sort_checked(deps)
print(order, is_topological(deps, order)) # ['pants', 'shoes', 'shirt', 'tie', 'jacket'] True
try:
topo_sort_checked({"a": ["b"], "b": ["c"], "c": ["a"]})
except ValueError as err:
print(err) # cycle detected via edge c -> aThe is_topological helper is the right way to test any topological sort, because it accepts every valid order and doesn't depend on the order neighbors are listed in.
Gotchas
- Vertices that appear only as targets. If
"jacket"shows up in a neighbor list but is not a key,graph[node]raisesKeyError. Add every vertex as a key, even with an empty list. - Recursion depth. CPython's default recursion limit is about 1000. A long dependency chain overflows it. Use the iterative version below.
- Determinism. The output depends on dictionary order and neighbor order. Sort the keys and neighbor lists if you need repeatable builds.
Iterative Version for Deep Graphs
A simple stack of vertices can't tell you when a vertex finishes. Push a (node, iterator) pair instead, so each frame remembers which neighbor comes next. A vertex finishes when its iterator runs out.
def topo_sort_iterative(graph):
visited = set()
postorder = []
for root in graph:
if root in visited:
continue
visited.add(root)
stack = [(root, iter(graph[root]))]
while stack:
node, neighbors = stack[-1]
for neighbor in neighbors:
if neighbor not in visited:
visited.add(neighbor)
stack.append((neighbor, iter(graph[neighbor])))
break
else: # iterator exhausted: node finishes
stack.pop()
postorder.append(node)
return postorder[::-1]
chain = {i: [i + 1] for i in range(100_000)}
chain[100_000] = []
order = topo_sort_iterative(chain)
print(order[:3], order[-1]) # [0, 1, 2] 100000DFS Versus Kahn's Algorithm
The other standard method is Kahn's algorithm. It repeatedly removes a vertex with no incoming edges (in-degree zero), using a queue.
| Aspect | DFS finish order | Kahn's algorithm |
|---|---|---|
| Time | O(V + E) | O(V + E) |
| Cycle signal | Finds a gray neighbor (back edge) and can name the edge | Fewer than V vertices get output |
| Extra data | Colors or a visited set | An in-degree count per vertex |
| Recursion risk | Yes, unless written iteratively | None |
| Natural extras | Feeds into Kosaraju's SCC algorithm | Easy to output vertices level by level, or the smallest available vertex first using a heap |
Choose DFS when you already have a DFS framework or need the finish order for later steps. Choose Kahn's when you want an order in "waves" of tasks that can run in parallel.
Exercise
Run topological_sort on {"a": ["c"], "b": ["c"], "c": ["d"], "d": []}. What does it return, and is it the only valid answer?
Show answer
DFS from a discovers c and then d. d finishes, then c, then a. Next, b finishes on its own. Post-order is [d, c, a, b], and the reverse is [b, a, c, d]. It is not the only answer, because [a, b, c, d] also satisfies every edge.
Exercise
Why can't a black neighbor ever break the property finish(v) < finish(u) for an edge u -> v?
Show answer
A black vertex has already finished, so it got its finish time earlier. u is still gray (open) while its edges are being scanned, so u will finish later. Therefore finish(v) < finish(u).
Exercise
A config maps each package to the packages it depends on, such as {"app": ["lib"], "lib": ["core"], "core": []}. Using the topological_sort function unchanged, how do you get an install order?
Show answer
The edges point from a package to its dependency, which is the reverse of "install before". The function returns ['app', 'lib', 'core']. Reverse that result, or use the post-order directly, to get ['core', 'lib', 'app'].