Sub topic 10
The Lexicographically Smallest Order
This chapter assumes you know Kahn's algorithm from earlier in the tutorial, Python's heapq module, and Big-O notation.
A DAG often has many valid topological orders. Most of the time any one of them is fine. Sometimes you need one specific, repeatable answer, for example when a test compares output to an expected string or a contest problem asks for "the smallest" order. The usual choice is the lexicographically smallest order. It is the order you get by comparing sequences element by element, the way a dictionary compares words: the first position where two orders differ decides which one is smaller.
The Greedy Idea
In Kahn's algorithm, the queue holds every node whose in-degree is currently zero. Any of these nodes can come next. A plain FIFO queue picks whichever one arrived first, so the result depends on insertion order.
To get the smallest order, always pick the smallest available node. A min-heap does this. It is a priority queue that always pops its smallest element.
This greedy choice is correct because every valid order has to start with one of the available nodes. Taking the smallest one gives the smallest possible first element. Once you remove that node, what is left is the same problem on a smaller graph, so the same argument applies at every step.
Implementation
import heapq
def smallest_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
heap = [u for u, d in indegree.items() if d == 0]
heapq.heapify(heap)
order = []
while heap:
u = heapq.heappop(heap)
order.append(u)
for v in graph.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
heapq.heappush(heap, v)
if len(order) != len(indegree):
raise ValueError("graph has a cycle")
return order
print(smallest_topo_order({3: [1], 2: [1], 1: [], 0: [2]}))
# [0, 2, 3, 1]Here is the trace. At the start, nodes 3 and 0 are available. The heap pops 0, and that frees node 2. Now the heap holds {2, 3}, so it pops 2. Then it pops 3, which frees node 1, and 1 comes last. A FIFO queue on the same dictionary would start with 3, because 3 was inserted first, and would return [3, 0, 2, 1].
Cost
Every node is pushed and popped once, and each heap operation costs O(log V). Edge processing stays O(1) per edge. The total is O(V log V + E), which falls within the usual O((V + E) log V) bound. Plain Kahn's algorithm runs in O(V + E), so the log factor is what you pay for a deterministic, smallest answer.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Mixing node types, such as `1` and `"a"` | `heapq` raises `TypeError` when it compares them | Use labels that can be compared with each other, or push `(key, node)` tuples |
| Sorting the initial zero-in-degree list but keeping a FIFO queue | Nodes freed later are not ordered correctly | Use a heap for the whole run |
| Confusing "lexicographically smallest" with "small labels as early as possible" | Wrong answer on some graphs | Treat them as separate problems (see the callout) |
Exercise
What does smallesttopoorder return for {"c": ["a"], "b": ["a"], "a": [], "d": ["b"]}?
Show answer
['c', 'd', 'b', 'a']. At the start only c and d have in-degree zero. The heap pops c, which lowers a's in-degree to 1. Next it pops d, which frees b. Then it pops b, which frees a, and a comes last.
Exercise
Why does replacing the heap with a list that you re-sort after every push still give the right answer, and why is it worse?
Show answer
It still picks the smallest available node each time, so it produces the same order. Each re-sort costs O(V log V) instead of O(log V) for a heap push, so the total cost can grow to O(V² log V).