Graphs and shortest paths · Algorithm 8 of 15
Topological Sort
Order dependencies and detect when a cycle makes an order impossible. Citation needed
The whole, before the parts
Topological sorting arranges tasks so that every prerequisite comes before the task that needs it. A course plan or build process is a useful example of the whole problem. Citation needed
Terminology and core concepts
A topological order puts every prerequisite before its dependent in a directed acyclic graph (DAG), a directed graph with no directed cycles. Kahn’s algorithm counts each vertex’s incoming edges, called its indegree. A zero-indegree vertex has no unfinished prerequisites, so it is safe to emit. Removing its outgoing edges may release more vertices. If vertices remain but none is ready, the remaining graph contains a cycle. Citation needed
Learning path
Trace an example
dependencies: read -> parse -> compile
fetch ---------> compile
initial indegrees: read 0, fetch 0, parse 1, compile 2
emit read parse becomes 0
emit fetch compile becomes 1
emit parse compile becomes 0
emit compile all four emitted
Implement it in Python
Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed
from collections import deque
def topological_sort(graph):
indegree = {v: 0 for v in graph}
for neighbors in graph.values():
for v in neighbors:
indegree[v] = indegree.get(v, 0) + 1
ready = deque(v for v in indegree if indegree[v] == 0)
order = []
while ready:
vertex = ready.popleft()
order.append(vertex)
for neighbor in graph.get(vertex, []):
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
ready.append(neighbor)
if len(order) != len(indegree):
raise ValueError('Directed cycle: no topological order')
return order
graph = {'read': ['parse'], 'fetch': ['compile'], 'parse': ['compile']}
assert topological_sort(graph) == ['read', 'fetch', 'parse', 'compile']
assert topological_sort({}) == []Citation needed
Analyze the cost
Counting edges and then removing each once costs O(V + E). The indegree table, queue, and output occupy O(V) extra space. Disconnected components are included when their vertices appear as keys or neighbors. Citation needed
A mistake to watch for
An edge must point from prerequisite to dependent for the output to have this meaning. If a cycle exists, a partial output is not a complete valid order. Citation needed
Practice and recall
-
What happens for edges A to B and B to A?
Work it out before opening the solution. Citation needed
Show the reasoning
- Both vertices have indegree 1.
- The ready queue is empty at the start.
- Zero of two vertices are emitted, so the algorithm raises a cycle error.
Citation needed
- What makes a vertex ready in Kahn’s algorithm?
- Its remaining indegree is zero. Citation needed
To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed
Sources
- MIT OpenCourseWare: Introduction to Algorithms — lecture notes — further study of the underlying algorithm and analysis.
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, Introduction to Algorithms — correctness arguments and complexity analysis.