Sub topic 9
When the Order Is Not Unique
This chapter assumes you know Kahn's algorithm from the earlier chapter, and that you can read adjacency lists in Python and reason about in-degrees.
A DAG usually has many valid topological orders. Every one of them respects every edge, so any of them is a correct answer. This matters in practice. Tests that compare your output with one fixed list can fail even when your code is right. Two runs of a build tool can also schedule tasks differently.
Where the Choice Comes From
A choice appears whenever two nodes have no path between them in either direction. Neither node has to come first, so either order is valid.
In this diamond graph, a must come first and d must come last. Nodes b and c can go in either order, so both a, b, c, d and a, c, b, d are valid.
In Kahn's algorithm, the choice shows up as a queue holding more than one node. Each node in the queue is ready to run, and the algorithm can pick any of them next. A deque takes them in insertion order, which depends on how you built the dictionary. That is an implementation detail and says nothing about the graph's structure.
The Uniqueness Condition
A topological order is unique exactly when, for every pair of consecutive nodes in the order, there is an edge from the first to the second. Put another way, the DAG contains a Hamiltonian path, which is a directed path that visits every node once.
The condition works in both directions:
- If such a path exists, its edges force each node to come before the next one, so only one arrangement is possible.
- If two consecutive nodes
u, vhave no edge between them, then no path can run fromutoveither, because any longer path would need an intermediate node placed between them. Swappinguandvtherefore gives a second valid order.
In terms of Kahn's algorithm, the order is unique if and only if the queue never holds more than one node.
Checking Uniqueness in Code
The version below adds a single check to Kahn's algorithm.
from collections import deque
def unique_topo_order(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
queue = deque(u for u, d in indegree.items() if d == 0)
order = []
unique = True
while queue:
if len(queue) > 1:
unique = False
u = queue.popleft()
order.append(u)
for v in graph.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) != len(indegree):
raise ValueError("graph has a cycle")
return order, unique
diamond = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
chain = {"a": ["b", "c"], "b": ["c"], "c": []}
print(unique_topo_order(diamond)) # (['a', 'b', 'c', 'd'], False)
print(unique_topo_order(chain)) # (['a', 'b', 'c'], True)The extra check adds only constant work per step, so the running time stays O(V + E). If you already have an order, you can check uniqueness without re-sorting. Confirm that each consecutive pair (order[i], order[i+1]) is an edge in the graph.
Common Mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Asserting output equals one hard-coded list | Other valid orders fail the test | Check that every edge `u -> v` has `u` before `v` |
| Assuming the DFS and Kahn results match | They break ties differently | Compare validity, not equality |
| Relying on dictionary order for stable output | Input order changes the result | Use a defined tie-break rule, covered in the next chapter |
Exercise
A graph has edges x -> y, y -> z, x -> z, and w -> z. Is its topological order unique? If not, how many valid orders are there?
Show answer
It is not unique. Both x and w start with in-degree 0, so Kahn's queue holds two nodes at the first step. The nodes x, y, z must appear in that order, and w can go anywhere before z. That gives 3 orders: w x y z, x w y z, and x y w z.
Exercise
You are given the order [p, q, r, s] for a DAG whose edges are p -> q, q -> r, p -> s, and r -> s. Without running any sort, decide whether this is the only valid order.
Show answer
Yes. Every consecutive pair is an edge: p -> q, q -> r, and r -> s. Together these edges form a Hamiltonian path, which fixes every position.