Sub topic 13
Listing and Counting All Topological Orders
Earlier chapters showed that a DAG can have many valid topological orders, and that Kahn's algorithm picks one of them depending on which ready node it takes first. This chapter answers two related questions. How do you list every valid order? And how many are there, without listing them all?
You should already know Kahn's algorithm, the in-degree bookkeeping it uses, recursion, Python generators (yield and yield from), and basic bit manipulation with &, |, and <<.
Why You Would Want Every Order
Most programs need one valid order and stop there. Listing all of them helps in a few specific situations:
- Testing. A scheduler or build tool may claim to work with any valid order. You can run it under every order of a small graph and confirm the results agree.
- Finding hidden dependencies. Suppose a build passes under one order and fails under another. The two tasks that swapped places probably have a dependency that the graph does not record.
- Puzzles and combinatorics. Some problems ask how many ways a set of tasks can be sequenced under precedence rules.
- Checking uniqueness. The order is unique exactly when the count is 1.
The catch is size. The number of orders can grow factorially with the number of nodes, so listing them only works for small graphs.
Enumerating Orders by Backtracking
Kahn's algorithm makes a choice at every step: any node with in-degree zero may come next. To get every order, try each choice in turn. Pick a ready node, update the in-degrees as Kahn's algorithm would, recurse, then undo the update and try the next ready node. This pattern is called backtracking.
def all_topo_orders(graph):
"""Yield every topological order of graph (u -> v means u before v)."""
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
nodes = list(indegree)
used = set()
order = []
def backtrack():
if len(order) == len(nodes):
yield list(order)
return
for u in nodes:
if u not in used and indegree[u] == 0:
# Choose u.
used.add(u)
order.append(u)
for v in graph.get(u, []):
indegree[v] -= 1
yield from backtrack()
# Undo the choice.
for v in graph.get(u, []):
indegree[v] += 1
order.pop()
used.remove(u)
yield from backtrack()
diamond = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
for order in all_topo_orders(diamond):
print(order)
# ['a', 'b', 'c', 'd']
# ['a', 'c', 'b', 'd']The function is a generator, so it hands back one order at a time. This matters because the full list may not fit in memory. A caller that only needs the first few orders can stop early with itertools.islice.
The yield list(order) line copies the order. If it yielded order itself, every caller would hold a reference to the same list, and that list ends up empty once backtracking finishes.
The Search Tree
Each path from the root to a leaf of the search tree is one complete order. A node branches once for every node that is ready at that step.
Edge Cases the Enumerator Handles
| Input | What happens | Number of orders yielded |
|---|---|---|
| Empty graph `{}` | `order` already has length 0, so the empty list is yielded once | 1 |
| A chain `a→b→c` | Exactly one node is ready at each step | 1 |
| `n` nodes with no edges | Every node is always ready | `n!` |
| Graph with a cycle | Nodes on the cycle never reach in-degree 0, so no branch reaches full length | 0 |
| Self-loop `a→a` | `a` starts with in-degree 1 and stays there | 0 |
| Duplicate edge listed twice | It is counted twice and decremented twice, so the result is still correct | Same as without the duplicate |
When the graph has a cycle, this version yields nothing instead of raising an error. Zero orders is the mathematically correct answer. If your caller would rather get an exception, run a cycle check (from the cycle detection chapter) first.
Cost of Enumeration
The output alone can be huge, so judge the enumerator by its cost per order. Each complete order needs V choices. Each choice scans up to V nodes to find the ready ones and updates the out-edges of the chosen node. That gives roughly O(V · (V + E)) work per order in this simple version. The total depends on how many orders exist:
| Nodes with no edges | Number of orders |
|---|---|
| 5 | 120 |
| 10 | 3,628,800 |
| 15 | about 1.3 × 10¹² |
| 20 | about 2.4 × 10¹⁸ |
Counting Without Listing
You may only need the number of orders. In that case there is a much faster method than enumerating, though it is still exponential.
The key observation is this. After you have placed some set S of nodes, the number of ways to finish the order depends only on which nodes are in S, not on the order they were placed in. That allows dynamic programming over subsets. Write each subset as a bitmask, an integer whose bit i is set when node i is in the subset.
Let ways[mask] be the number of valid ways to place exactly the nodes in mask first. Node i can be added to mask when it is not already in it and all of its predecessors are in it.
def count_topo_orders(graph):
"""Count topological orders using DP over subsets of placed nodes."""
nodes = list(dict.fromkeys(
list(graph) + [v for targets in graph.values() for v in targets]
))
index = {u: i for i, u in enumerate(nodes)}
n = len(nodes)
# pred_mask[i] has a bit set for every predecessor of node i.
pred_mask = [0] * n
for u, targets in graph.items():
for v in targets:
pred_mask[index[v]] |= 1 << index[u]
ways = [0] * (1 << n)
ways[0] = 1
for mask in range(1 << n):
if ways[mask] == 0:
continue
for i in range(n):
bit = 1 << i
if (mask & bit) == 0 and (pred_mask[i] & mask) == pred_mask[i]:
ways[mask | bit] += ways[mask]
return ways[(1 << n) - 1]
print(count_topo_orders({"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []})) # 2
print(count_topo_orders({"w": [], "x": [], "y": [], "z": []})) # 24
print(count_topo_orders({"a": ["b"], "b": ["c"], "c": []})) # 1
print(count_topo_orders({"a": ["b"], "b": ["a"]})) # 0Why the Loop Order Is Safe
Adding a bit to mask always produces a larger integer. So by the time the outer loop reaches any mask, every smaller subset that leads into it has already been processed, and ways[mask] is final. This is the same idea as relaxing edges in topological order. The subsets form a DAG, and plain numeric order is a valid topological order of that DAG.
Correctness on Cycles and Self-Loops
If nodes form a cycle, each node on the cycle needs another one placed before it, so none of them can ever be added. The full mask is never reached and the function returns 0. A self-loop puts node i's own bit in pred_mask[i]. Node i can only be added when that bit is not yet in mask, so the predecessor condition never holds, and the result is again 0.
Cost of Counting
The table has 2^V entries and each entry checks V nodes, so the time is O(2^V · V) and the memory is O(2^V). In pure Python this works up to roughly 20–22 nodes. At 20 nodes that is about 20 million inner steps and a table of about a million integers. The enumerator, by contrast, could need on the order of 10¹⁸ steps for the same graph.
A Shortcut for Independent Parts
If the graph splits into separate components with no edges between them, you can count each component on its own and then combine the counts. Say the components have sizes n₁, …, nk and order counts c₁, …, ck. The total is
(n₁ + … + nk)! / (n₁! · … · nk!) × c₁ × … × c_k
The fraction counts the ways to interleave the components' sequences, and each component's internal order can be chosen independently. Splitting a 30-node graph into three 10-node components turns one impossible 2³⁰-entry table into three tables of 2¹⁰ entries each.
Choosing an Approach
| Goal | Method | Practical limit |
|---|---|---|
| Is the order unique? | Kahn's algorithm, checking whether the queue ever holds more than one node | Any size, O(V + E) |
| Get the first k orders | `all_topo_orders` with `itertools.islice` | Any size, if k is small |
| List all orders | `all_topo_orders` | Total count in the thousands or low millions |
| Count all orders exactly | Subset DP | About 20–22 nodes in Python |
| Count orders of a large graph | Split into components, or estimate by sampling | Depends on the graph's structure |
Exercise
The graph {"a": ["b"], "b": [], "c": []} has one edge, a → b, and an isolated node c. How many topological orders does it have? List them, and check your count with the component formula.
Show answer
There are 3 orders: [a, b, c], [a, c, b], and [c, a, b]. Using the formula, the components are {a, b} with 1 internal order and {c} with 1 internal order. The interleavings number 3! / (2! · 1!) = 3, and 3 × 1 × 1 = 3.
Exercise
In alltopoorders, what goes wrong if you delete the "undo" loop that adds 1 back to each indegree[v]?
Show answer
After the first branch returns, the in-degrees of the chosen node's successors stay too low. Later branches then treat those successors as ready before their predecessors have been placed. The function yields invalid orders, and some valid orders can be missed or produced more than once.
Exercise
Modify counttopoorders mentally. Why is it correct to skip masks where ways[mask] == 0, and which masks have this property?
Show answer
A mask with zero ways contributes nothing when it is added to its supersets, so skipping it changes no result and saves time. These masks are subsets that are not "downward closed": they contain some node without containing all of that node's predecessors. No valid prefix of an order can place exactly that set.
Exercise
You need to know whether a 5,000-node build graph has exactly one valid order. Which method do you use, and why not counttopoorders?
Show answer
Run Kahn's algorithm and check whether the queue ever holds two or more nodes at once. If it never does and all nodes get processed, the order is unique. This takes O(V + E) time. counttopoorders would need a table of 2^5000 entries, which is impossible.