Sub topic 3
When the Order Is Not Unique
This chapter assumes you already know Kahn's algorithm, in-degree counts, and the BFS and DFS traversals.
When the Order Is Not Unique
A DAG often has many valid topological orders. In Kahn's algorithm, any time the queue holds two or more nodes, you could take either one next. The order is unique exactly when the queue never holds more than one node. An equivalent test is that every consecutive pair in the order is joined by an edge, so the order forms a single path through every node.
The Lexicographically Smallest Order
To get the smallest order, replace the queue with a min-heap. Each step then takes the smallest available node. The heap adds a log factor, so the running time is O((V + E) log V).
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]Grouping Tasks into Parallel Levels
You can also run Kahn's algorithm in rounds. Each round removes every node whose in-degree is currently zero. The nodes removed in the same round do not depend on each other, so they can run in parallel. The number of rounds equals the number of nodes on the longest path.
Dynamic Programming on DAGs: Longest Paths
Process the nodes in topological order and set dist[v] = max(dist[v], dist[u] + 1) for each edge u → v. When you reach a node, all of its predecessors are already final, so this takes O(V + E). On general graphs, the longest-path problem is NP-hard.
Listing and Counting All Topological Orders
To list every order, use backtracking. At each step, try every node whose in-degree is zero, recurse, and then undo the choice. The number of orders can grow factorially. For example, n nodes with no edges have n! orders. Use this only on small graphs.
Using Python's graphlib.TopologicalSorter
graphlib.TopologicalSorter takes a mapping from each node to its predecessors. This is the reverse of the adjacency lists used above.
from graphlib import TopologicalSorter, CycleError
deps = {"app": {"lib", "config"}, "lib": {"utils"}, "config": set(), "utils": set()}
try:
print(list(TopologicalSorter(deps).static_order()))
except CycleError as err:
print("cycle:", err.args[1])Topological Sort in Real Systems
- Build tools (Make, Bazel) compile targets after their inputs.
- Schedulers (Airflow) run each task after its upstream tasks, one level at a time.
- Package managers and course planners install packages, or schedule courses, after their prerequisites. They report a cycle as an error.
Exercise
The graph has edges a → b, a → c, and b → c. Is its topological order unique?
Show answer
Yes. The only order is a, b, c. Every consecutive pair is joined by an edge, and Kahn's queue never holds more than one node.