Sub topic 10
The Lexicographically Smallest Order
A DAG usually has many valid topological orders. Most of the time any of them works, but sometimes you need one specific order that everyone can reproduce. Examples include a judge that checks contest answers by exact match, a build log that should look the same on every run, or a course planner that lists lower-numbered courses first whenever the prerequisites allow it. The usual tie-breaking rule is to pick the lexicographically smallest order, the one that would come first if you sorted every valid order like words in a dictionary.
This chapter assumes you already know Kahn's algorithm from earlier in the tutorial, how a binary heap (priority queue) works, and Python's heapq module. It also assumes you understand why topological orders are often not unique.
What "lexicographically smallest" means
You compare two sequences position by position. At the first position where they differ, the sequence with the smaller element is the smaller sequence. For example, [0, 2, 3, 1] is smaller than [0, 3, 2, 1] because they first differ at index 1, and 2 < 3.
Among all topological orders of a DAG, exactly one is lexicographically smallest. To find it, the first element must be as small as possible. Given that first element, the second must be as small as possible, and so on down the sequence.
The idea: swap the queue for a min-heap
Kahn's algorithm keeps a collection of available nodes, meaning nodes whose in-degree has dropped to zero. At each step it removes one of them. A FIFO queue removes whichever node became available first. A min-heap removes the smallest available node instead. That one change is enough.
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]The cycle check is unchanged from plain Kahn's algorithm. A node on a cycle never reaches in-degree zero, so it never enters the heap, and the output comes up short.
Tracing the example
The graph has edges 0 → 2, 2 → 1, and 3 → 1.
| Step | Heap before pop | Popped | In-degree changes | Order so far |
|---|---|---|---|---|
| 1 | {0, 3} | 0 | 2: 1 → 0, push 2 | [0] |
| 2 | {2, 3} | 2 | 1: 2 → 1 | [0, 2] |
| 3 | {3} | 3 | 1: 1 → 0, push 1 | [0, 2, 3] |
| 4 | {1} | 1 | none | [0, 2, 3, 1] |
At step 2 a FIFO queue would have produced 3 next, because 3 was available before 2. The heap picks 2 because 2 < 3.
Why the greedy choice is correct
Suppose the greedy order G and some other valid order O share the same first i elements. Both orders have then removed the same set of nodes, so they face the same set of available nodes at position i. Any valid order has to place an available node at position i, because a node with an unplaced predecessor cannot go there. G places the minimum of that set. So O's element at position i is either equal to G's, or larger, which makes O lexicographically larger. Because this holds at every position, no valid order is smaller than G.
There is a second fact behind this argument. Taking one available node never makes another available node unavailable. Removing a node only lowers in-degrees, so the available set can only gain members. A small choice now never blocks a choice you would have wanted later, which is why the greedy rule never has to backtrack.
Cost
Each node is pushed once and popped once, and each heap operation costs O(log V). Each edge causes one constant-time decrement. The total is O(V log V + E), which is within the O((V + E) log V) bound often quoted for this algorithm. Space stays at O(V + E) for the graph, the in-degree map, and the heap.
The log V factor is the price of choosing among available nodes. When determinism matters but "smallest" does not, plain Kahn's algorithm with a fixed insertion order is already deterministic and runs in O(V + E).
Custom priorities
Your nodes may not be integers, or "smallest" may mean something other than natural order, such as the shortest estimated build time first. In that case, push tuples of (priority, node). The node itself acts as the tie-breaker, which keeps the result deterministic.
import heapq
def topo_order_by_key(graph, key):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
heap = [(key(u), 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, (key(v), v))
if len(order) != len(indegree):
raise ValueError("graph has a cycle")
return order
build_minutes = {"fetch": 1, "lint": 2, "compile": 5, "test": 3}
graph = {"fetch": ["compile", "lint"], "compile": ["test"], "lint": ["test"], "test": []}
print(topo_order_by_key(graph, build_minutes.get))
# ['fetch', 'lint', 'compile', 'test']A different problem that looks similar
Some tasks ask for something else: "put node 1 as early as possible, then put node 2 as early as possible given that, and so on." This is not the same as the lexicographically smallest order. Take nodes 1, 2, 3 with the single edge 3 → 1:
| Goal | Result |
|---|---|
| Lexicographically smallest | [2, 3, 1] |
| Smallest labels as early as possible | [3, 1, 2] |
The min-heap picks 2 first, because 1 is not available yet. That pushes node 1 to the last position. To place small labels early, reverse every edge, run Kahn's algorithm with a max-heap, and reverse the output. Working backward, the algorithm puts the largest labels as late as possible, and that leaves the earliest slots for the small labels.
import heapq
def small_labels_early(graph):
reverse = {u: [] for u in graph}
for u in graph:
for v in graph[u]:
reverse.setdefault(v, []).append(u)
indegree = {u: 0 for u in reverse}
for u in reverse:
for v in reverse[u]:
indegree[v] += 1
heap = [-u for u, d in indegree.items() if d == 0] # negate for a max-heap
heapq.heapify(heap)
order = []
while heap:
u = -heapq.heappop(heap)
order.append(u)
for v in reverse[u]:
indegree[v] -= 1
if indegree[v] == 0:
heapq.heappush(heap, -v)
if len(order) != len(indegree):
raise ValueError("graph has a cycle")
order.reverse()
return order
print(smallest_topo_order({1: [], 2: [], 3: [1]})) # [2, 3, 1]
print(small_labels_early({1: [], 2: [], 3: [1]})) # [3, 1, 2]Negating values to simulate a max-heap only works for numbers. For other labels, use a key that reverses the order, or wrap each label in a small class whose __lt__ method is inverted.
Common mistakes
- Sorting the output of plain Kahn's algorithm. Sorting the result breaks the dependency constraints. The order must be chosen step by step, not fixed afterward.
- Sorting only the initial sources. Sorting the starting queue once and then appending to it as a FIFO ignores nodes that become available later. In the trace above, that approach outputs 3 before 2.
- Assuming DFS with sorted neighbors gives the same answer. It gives a deterministic order, but usually not the smallest one.
- Solving the wrong variant. Check whether the task wants the lexicographically smallest sequence or wants small labels placed early. They differ, as the 3 → 1 example shows.
Exercise
Compute the lexicographically smallest topological order of the graph with edges 5→11, 7→11, 7→8, 3→8, 3→10, 11→2, 11→9, 11→10, 8→9.
Show answer
[3, 5, 7, 8, 11, 2, 9, 10]. The heap starts as {3, 5, 7}. Popping 3, 5, and 7 in turn brings 11 and 8 to in-degree zero. Popping 8 lowers 9 to in-degree 1. Popping 11 makes 2, 9, and 10 available, and they come out in that order.
Exercise
A teammate sorts the initial zero-in-degree nodes, then runs ordinary Kahn's algorithm with a FIFO queue. Give a graph where this does not produce the lexicographically smallest order.
Show answer
Use the edges 0→2, 2→1, 3→1. The sorted start queue is [0, 3]. Popping 0 appends 2 behind 3, so the FIFO result is [0, 3, 2, 1]. The smallest order is [0, 2, 3, 1]. Nodes that become available later must still compete with the ones already waiting, and only a priority queue handles that.
Exercise
What is the running time of the min-heap version on a graph with V nodes and E edges, and why is it not O(V + E)?
Show answer
O(V log V + E). Each of the V nodes is pushed and popped once, at O(log V) per heap operation, and each edge causes one O(1) in-degree decrement. The log factor comes from choosing the minimum among the available nodes, which a FIFO queue never has to do.