Sub topic 9
When the Order Is Not Unique
This chapter assumes you can already compute a topological order with Kahn's algorithm or with depth-first search (DFS), and that you can check whether a given sequence is a valid order. Most DAGs have many valid orders. This chapter covers why that happens, the exact condition under which only one order exists, how to test for that condition in linear time, and the bugs that come from expecting one particular order.
One Graph, Several Correct Answers
Take the course prerequisite graph from earlier chapters. intro comes before both data_structures and discrete_math, and both of those come before algorithms.
Kahn's algorithm, with the dictionary in the order shown in the earlier chapter, returns:
['intro', 'data_structures', 'discrete_math', 'algorithms']DFS on the same dictionary visits data_structures first, finishes it first, and then reverses the finishing order. The result is:
['intro', 'discrete_math', 'data_structures', 'algorithms']Both answers are correct. The definition of a topological order only requires that every edge u -> v has u placed before v. No edge connects data_structures and discrete_math, so the definition says nothing about which of the two comes first.
The general principle is that a topological order is any linear extension of the partial order defined by the edges. If two nodes are not connected by a directed path in either direction, they are incomparable, and any valid order may place them either way.
How Many Orders Can There Be?
The number of valid orders ranges from 1 to n!, depending on how tightly the edges constrain the nodes.
| Graph shape (n nodes) | Example edges | Number of topological orders |
|---|---|---|
| Single chain | a→b→c→d | 1 |
| Diamond | a→b, a→c, b→d, c→d | 2 |
| Two independent chains of 2 | a→b, c→d | 6 |
| No edges at all | none | n! (24 for n = 4) |
The two-chains row comes from choosing which 2 of the 4 positions hold a and b. That is C(4, 2) = 6 ways, and the order inside each chain is fixed. With no edges at all, every permutation is valid. A later chapter lists and counts all orders for small graphs. Here the question is narrower: when is there exactly one?
The Uniqueness Condition
A DAG has exactly one topological order if and only if it contains a Hamiltonian path, meaning a directed path that visits every node exactly once.
An equivalent condition is easier to test: take any topological order v1, v2, ..., vn. The order is unique if and only if every consecutive pair (vi, vi+1) is joined by the edge vi -> vi+1.
Why a Missing Consecutive Edge Means Another Order Exists
Suppose vi and vi+1 are adjacent in a valid order and there is no edge vi -> vi+1. There is also no edge vi+1 -> vi, because that edge would point backward and the order would not be valid. Swap the two nodes. Every other node keeps its position relative to both of them, so every edge that involves a third node is still satisfied. No edge connects the swapped pair. The new sequence is therefore valid and different.
Why Consecutive Edges Force the Order
If every consecutive pair is joined by an edge, those edges form a path v1 -> v2 -> ... -> vn through all nodes. Any valid order must respect each of those edges, so v1 comes before v2, which comes before v3, and so on. Only one sequence satisfies all of them.
Extra edges such as a -> c above do not matter. Only the presence of a path through every node matters.
Testing Uniqueness Inside Kahn's Algorithm
Kahn's algorithm gives a direct way to see the condition. At each step the queue holds every node whose remaining in-degree is zero. If the queue ever holds two or more nodes, either one could be output next. Two different choices produce two different orders, so the order is not unique. If the queue never holds more than one node, the algorithm had no choices, and the order it produced is the only one.
from collections import deque
def topo_sort_with_uniqueness(graph):
"""Return (order, unique). graph maps u to the nodes v with u -> v."""
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
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
print(topo_sort_with_uniqueness(courses))
# (['intro', 'data_structures', 'discrete_math', 'algorithms'], False)
chain = {"a": ["b", "c"], "b": ["c"], "c": []}
print(topo_sort_with_uniqueness(chain))
# (['a', 'b', 'c'], True)The extra check costs O(1) per iteration, so the whole function still runs in O(V + E). The function does not stop at the first sign of non-uniqueness, because it still needs the full order to detect a cycle. A cyclic graph has zero orders, and the function reports that case instead of returning unique = False.
Testing an Order You Already Have
If an order was produced elsewhere, for example by DFS or by a library, you can test the consecutive-edge condition directly. When the test fails, the function below also returns a pair that can be swapped, which proves that a second order exists.
def find_swappable_pair(graph, order):
"""Return (i, i+1) for adjacent nodes with no edge between them, or None if the order is unique."""
succ = {u: set(vs) for u, vs in graph.items()}
for i in range(len(order) - 1):
if order[i + 1] not in succ.get(order[i], set()):
return i, i + 1
return None
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
order = ["intro", "data_structures", "discrete_math", "algorithms"]
pair = find_swappable_pair(courses, order)
print(pair)
# (1, 2)
i, j = pair
other = order[:]
other[i], other[j] = other[j], other[i]
print(other)
# ['intro', 'discrete_math', 'data_structures', 'algorithms']This test is only correct when order is already a valid topological order. On an invalid sequence it can return any answer.
Common Errors Caused by Non-Uniqueness
Asserting an Exact Order in Tests
A test like assert topo_sort(g) == ["a", "b", "c", "d"] passes until someone changes the insertion order of a dictionary, switches from Kahn's algorithm to DFS, or upgrades a library. The algorithm was correct each time, and only the tie-breaking changed. Test the property you care about instead:
def is_topological_order(graph, order):
nodes = set(graph) | {v for vs in graph.values() for v in vs}
if len(order) != len(nodes) or set(order) != nodes:
return False
pos = {u: i for i, u in enumerate(order)}
return all(pos[u] < pos[v] for u in graph for v in graph[u])
g = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(is_topological_order(g, ["a", "c", "b", "d"])) # True
print(is_topological_order(g, ["a", "d", "b", "c"])) # FalseReading Dependencies from Positions
Position in the order is not a dependency relation. When x comes before y, either x must precede y, or the two are unrelated and the algorithm happened to place x first. Code that treats "earlier in the order" as "required by" will invent dependencies that do not exist. For example, it might rebuild discrete_math whenever data_structures changes.
Non-Reproducible Output
Build logs, generated files, and migration scripts that come from a topological sort can differ between runs or machines if the input iteration order varies. In Python 3.7 and later, dictionaries keep insertion order, but sets do not keep a stable order for strings across processes, because string hashing is randomized. If you need reproducible output, fix the tie-breaking rule. The usual choice is to always take the smallest available node, which is the subject of the next chapter.
Exercises
Exercise
The graph has edges a→b, a→c, b→d, c→d, and b→c. Is its topological order unique? If so, give it and name the Hamiltonian path.
Show answer
Yes. The edge b→c removes the only freedom in the diamond. The single order is a, b, c, d, and the Hamiltonian path is a→b→c→d. In Kahn's algorithm the queue holds a, then b (c still waits on b), then c, then d, so it never holds more than one node.
Exercise
A colleague says: "If Kahn's algorithm and DFS return the same order for my graph, the order must be unique." Is that right?
Show answer
No. The two algorithms can make the same choices by coincidence. For the graph with edges a→b and a→c, where the adjacency list for a is ["c", "b"], Kahn's algorithm gives a, c, b. DFS visits c first, finishes it, then finishes b, so its reversed finishing order is a, b, c. With the list ["b", "c"] Kahn gives a, b, c and DFS gives a, c, b. Other inputs can make the two agree while a second order still exists. Uniqueness depends only on the consecutive-edge condition.
Exercise
How many topological orders does a graph with 5 nodes have if its only edges are a→b and c→d, and node e is isolated?
Show answer
30. There are 5! = 120 permutations. Half of them put a before b, and of those, half put c before d. The constraints are independent, so the count is 120 / 2 / 2 = 30.