Sub topic 5
Kahn's Algorithm
This chapter assumes you can read Python and know what an adjacency list is. It also assumes you are comfortable with queues and breadth-first search, and that you remember from earlier chapters that a topological order exists exactly when the graph is a DAG. Here you will turn that fact into a working algorithm.
The Core Idea
Look at any DAG and ask which task can go first. The answer is any node with no incoming edges. Nothing has to happen before it. A node like that is called a source, and its in-degree (the number of edges pointing into it) is zero.
Kahn's algorithm, published by Arthur Kahn in 1962, repeats one step:
- Pick a node whose in-degree is zero.
- Append it to the output.
- Delete it from the graph, together with its outgoing edges.
Deleting a node never creates a cycle, so what remains is still a DAG. The previous chapter showed that every non-empty DAG has at least one source, so the algorithm can always continue until the graph is empty.
The algorithm does not actually delete anything from the graph. It keeps a count of remaining incoming edges for each node. "Deleting" node u means subtracting one from the count of each successor of u. When a count drops to zero, that successor becomes a new source and joins a queue of ready nodes.
The Implementation
The function below takes a successor map, so graph[u] lists the nodes that must come after u. An edge u -> v means "u before v".
from collections import deque
def topo_sort_kahn(graph):
"""graph maps each node to a list of nodes that depend on it (u -> v means u before 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 = []
while queue:
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
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
print(topo_sort_kahn(courses))
# ['intro', 'data_structures', 'discrete_math', 'algorithms']A few details in this code matter:
indegree.get(v, 0)registers nodes that appear only as edge targets and never as keys. Without it, such a node would raise aKeyError.graph.get(u, [])handles the same case from the other side. A node that is only a target has no successor list.- The final length check is how the algorithm reports a cycle. The next chapter explains why this check is enough.
Tracing the Algorithm
Running through the course example by hand shows how the in-degree counts change at each step. Initially, intro has in-degree 0, data_structures and discrete_math have 1, and algorithms has 2.
| Step | Dequeued | In-degree changes | Queue after step | Order so far |
|---|---|---|---|---|
| 0 | none | initial counts | intro | (empty) |
| 1 | intro | data_structures 1→0, discrete_math 1→0 | data_structures, discrete_math | intro |
| 2 | data_structures | algorithms 2→1 | discrete_math | intro, data_structures |
| 3 | discrete_math | algorithms 1→0 | algorithms | intro, data_structures, discrete_math |
| 4 | algorithms | none | (empty) | intro, data_structures, discrete_math, algorithms |
algorithms enters the queue only after both of its prerequisites have been output. That property is what makes the result correct.
Why the Output Is Correct
The argument rests on one invariant: a node enters the queue only when all of its predecessors are already in the output.
In-degree counts start at the number of predecessors. A count goes down by one each time one of those predecessors is output, and a node is enqueued exactly when its count reaches zero. So when any node v is appended to the order, every u with an edge u -> v already came earlier. That is the definition of a topological order.
Completeness is the other half. If the graph is a DAG, the nodes that have not been output yet form a smaller DAG, and that DAG has a source. That source's count has reached zero, so it is in the queue. The queue therefore cannot empty early, and every node gets output.
Working from an Edge List
Dependency data often comes as pairs instead of an adjacency map. Building the successor lists and the counts in one pass is straightforward:
from collections import deque, defaultdict
def kahn_from_edges(nodes, edges):
succ = defaultdict(list)
indegree = {u: 0 for u in nodes}
for u, v in edges:
succ[u].append(v)
indegree[v] += 1 # KeyError if v is not a declared node
queue = deque(u for u in nodes if indegree[u] == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in succ[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) != len(nodes):
raise ValueError("graph has a cycle")
return order
nodes = ["shirt", "tie", "jacket", "belt", "pants"]
edges = [("shirt", "tie"), ("tie", "jacket"), ("pants", "belt"),
("belt", "jacket"), ("shirt", "belt")]
print(kahn_from_edges(nodes, edges))
# ['shirt', 'pants', 'tie', 'belt', 'jacket']The explicit nodes list does two jobs. It includes isolated nodes that have no edges, which an edge list alone would lose. It also makes typos in edge endpoints fail loudly instead of silently adding a new node.
Checking a Result
When you test your own implementation, check the output against the definition. Don't compare it with one expected list, because many orders can be valid.
def is_topological_order(graph, order):
nodes = set(graph) | {v for u in graph for v in graph[u]}
if len(order) != len(set(order)) 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])
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
print(is_topological_order(courses, ["intro", "discrete_math", "data_structures", "algorithms"])) # True
print(is_topological_order(courses, ["intro", "algorithms", "discrete_math", "data_structures"])) # FalseCommon Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Edge direction reversed (map holds predecessors, code treats them as successors) | Output is exactly backwards | Decide what `u -> v` means and document it in the docstring. Reverse the map if needed |
| Initializing in-degrees only from dictionary keys | `KeyError` on nodes that appear only as targets | Use `indegree.get(v, 0)` or declare all nodes up front |
| Using `list.pop(0)` as the queue | Correct output, quadratic time on large graphs | Use `collections.deque` and `popleft()` |
| Enqueuing a node when its count is "less than or equal to" zero | Duplicates in the output | Enqueue only at the moment the count becomes exactly zero |
| Omitting the final length check | A cyclic graph silently returns a partial order | Compare `len(order)` with the node count |
| Deduplicating edges in one place but not the other | Counts never reach zero | Count and decrement every edge the same way. Duplicate edges are harmless if handled consistently |
The Queue Is a Choice
Nothing in the correctness argument depends on the queue being first-in, first-out. Any container of ready nodes works: a stack, a set, or a priority queue. Each choice gives a valid topological order, but the orders can differ. Later chapters use this freedom. A min-heap produces the lexicographically smallest order, and processing the queue one batch at a time groups tasks into levels that can run in parallel. The running time, linear in nodes plus edges with a deque, is analyzed in its own chapter.
Exercise
Run Kahn's algorithm by hand on the graph {"a": ["c"], "b": ["c", "d"], "c": ["e"], "d": ["e"], "e": []} using a FIFO queue, and give the output order.
Show answer
Initial in-degrees: a 0, b 0, c 2, d 1, e 2. The queue starts as [a, b]. Dequeue a: c drops to 1. Dequeue b: c drops to 0 and is enqueued, then d drops to 0 and is enqueued. Dequeue c: e drops to 1. Dequeue d: e drops to 0 and is enqueued. Dequeue e. The order is ['a', 'b', 'c', 'd', 'e'].
Exercise
Your input is a predecessor map, where deps[v] is the set of nodes that must come before v. Without building a reversed graph first, what must change in toposortkahn?
Show answer
The in-degree of v is now simply len(deps[v]), but you still need successor lists to know whose counts to decrement when u is output. So you either build a successor map anyway, or scan every node's predecessor set after each step, which costs O(V) per step and O(V^2) overall. The usual fix is to invert the map once in O(V + E) and then run the standard algorithm.
Exercise
Someone replaces deque with a Python list used as a stack (append and pop from the end). Is the output still a valid topological order? Explain using the invariant.
Show answer
Yes. The invariant says a node is added to the container only after all its predecessors are output, and that holds regardless of the order in which nodes leave the container. The stack only changes which valid order you get. For the course graph it gives ['intro', 'discretemath', 'datastructures', 'algorithms'].