Skip to content

Topological order and dependencies

A dependency order puts each prerequisite before the tasks that require it. A directed edge A -> B means that A must finish before B starts. A topological order includes every vertex once and respects every such edge.

This lesson uses an invented analysis plan. Reads and a reference precede alignment, alignment precedes counts, and counts precede a report. A separate metadata task has no dependencies. The graph describes these ordering rules; it does not execute an analysis.

Download the English captions for this video.

An adjacency dictionary lists outgoing edges. Its keys include every vertex, including vertices with no outgoing edges. The indegree of a vertex counts its incoming edges. Initially, an indegree of zero identifies a task with no prerequisites.

Kahn’s algorithm keeps zero-indegree vertices in a queue. After it emits a vertex, it removes that vertex’s outgoing edges from the remaining indegrees. A neighbor enters the queue when its indegree reaches zero.

from collections import deque
def topological_order(
graph: dict[str, list[str]], trace: bool = False
) -> list[str]:
"""Order a directed graph so prerequisites precede dependents.
Args:
graph: Outgoing adjacency lists with every vertex present as a key.
Repeated edges are counted and removed with their multiplicity.
The input is not modified.
trace: Whether to print the queue and remaining indegrees.
Returns:
Each vertex once in a valid dependency order. Dictionary and neighbor
order break ties between vertices that are ready at the same time.
Raises:
ValueError: If an edge names an absent vertex or a cycle prevents a
complete ordering.
"""
indegree = {vertex: 0 for vertex in graph}
for neighbors in graph.values():
for neighbor in neighbors:
if neighbor not in graph:
raise ValueError("every neighbor must be a graph vertex")
indegree[neighbor] += 1
ready = deque(vertex for vertex in graph if indegree[vertex] == 0)
order: list[str] = []
if trace:
print("Initial indegrees:", indegree)
print("Initial queue:", list(ready))
while ready:
vertex = ready.popleft()
order.append(vertex)
for neighbor in graph[vertex]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
ready.append(neighbor)
if trace:
print("Emit", vertex, "queue", list(ready))
print("Remaining indegrees:", indegree)
if len(order) != len(graph):
raise ValueError("graph contains a directed cycle")
return order
graph = {
"reads": ["align"],
"reference": ["align"],
"align": ["count"],
"count": ["report"],
"report": [],
"metadata": [],
}
snapshot = {vertex: neighbors.copy() for vertex, neighbors in graph.items()}
order = topological_order(graph, trace=True)
print("Dependency order:", order)
assert graph == snapshot
Initial indegrees: {'reads': 0, 'reference': 0, 'align': 2, 'count': 1, 'report': 1, 'metadata': 0}
Initial queue: ['reads', 'reference', 'metadata']
Emit reads queue ['reference', 'metadata']
Remaining indegrees: {'reads': 0, 'reference': 0, 'align': 1, 'count': 1, 'report': 1, 'metadata': 0}
Emit reference queue ['metadata', 'align']
Remaining indegrees: {'reads': 0, 'reference': 0, 'align': 0, 'count': 1, 'report': 1, 'metadata': 0}
Emit metadata queue ['align']
Remaining indegrees: {'reads': 0, 'reference': 0, 'align': 0, 'count': 1, 'report': 1, 'metadata': 0}
Emit align queue ['count']
Remaining indegrees: {'reads': 0, 'reference': 0, 'align': 0, 'count': 0, 'report': 1, 'metadata': 0}
Emit count queue ['report']
Remaining indegrees: {'reads': 0, 'reference': 0, 'align': 0, 'count': 0, 'report': 0, 'metadata': 0}
Emit report queue []
Remaining indegrees: {'reads': 0, 'reference': 0, 'align': 0, 'count': 0, 'report': 0, 'metadata': 0}
Dependency order: ['reads', 'reference', 'metadata', 'align', 'count', 'report']

align enters the queue only after both prerequisites leave it. The metadata task starts ready even though no other vertex can reach it. Starting from only one chosen vertex would omit this disconnected task.

For every unprocessed vertex, its indegree equals its incoming edge count from unprocessed vertices. Removing one emitted vertex removes exactly its outgoing edges, so the invariant remains true. Every queued vertex therefore has all its prerequisites in the output already.

A finite directed graph without a cycle always has a zero-indegree vertex. Otherwise, repeatedly following a predecessor would revisit a vertex and form a directed cycle. This argument also applies to the graph that remains after each removal.

If the queue empties before every vertex appears, the remaining graph contains a directed cycle. Some blocked vertices can lie downstream of that cycle. They need not belong to the cycle themselves. Returning the partial output would incorrectly report success.

print("Empty graph:", topological_order({}))
print("Independent tasks:", topological_order({"A": [], "B": [], "C": []}))
print("Repeated edge:", topological_order({"A": ["B", "B"], "B": []}))
invalid_graphs = {
"Cycle with a blocked dependent": {
"A": ["B"], "B": ["A", "C"], "C": [], "D": []
},
"Self-loop": {"A": ["A"]},
"Absent neighbor": {"A": ["B"]},
}
for label, invalid_graph in invalid_graphs.items():
try:
topological_order(invalid_graph)
except ValueError as error:
print(f"{label}: {error}")
else:
raise AssertionError("invalid graph was accepted")
positions = {vertex: index for index, vertex in enumerate(order)}
assert len(order) == len(graph)
assert set(order) == set(graph)
for prerequisite, dependents in graph.items():
for dependent in dependents:
assert positions[prerequisite] < positions[dependent]
print("Every dependency precedes its dependent.")
Empty graph: []
Independent tasks: ['A', 'B', 'C']
Repeated edge: ['A', 'B']
Cycle with a blocked dependent: graph contains a directed cycle
Self-loop: graph contains a directed cycle
Absent neighbor: every neighbor must be a graph vertex
Every dependency precedes its dependent.

A visited set alone cannot make this cycle decision. An already visited vertex can be a shared dependent in an acyclic graph. A DFS alternative distinguishes vertices still on the active path from vertices whose exploration is complete.

Several topological orders can satisfy the same graph. The queue uses dictionary and neighbor order to resolve choices. It does not promise alphabetical order or the only possible order. If a problem requires the smallest available label, use a min-heap instead of a queue.

Let V be the vertex count and E the number of adjacency entries, including repeated edges. The function counts every edge once and removes it once. Each vertex enters and leaves the queue once, so expected time is O(V + E). This bound assumes constant-time dictionary operations on bounded-size keys.

The indegrees and queue use O(V) auxiliary space. The returned order uses another O(V) space, and the input graph uses O(V + E) space. The graph remains unchanged. Trace mode prints every indegree after each removal and can add O(V²) display work; the linear bound applies when trace=False.

A min-heap changes the bound to O(E + V log V) with constant-time label comparisons. A topological order specifies precedence only. It does not choose an optimal schedule for task durations or limited workers.

Recognize the standard library representation

Section titled “Recognize the standard library representation”

Python provides graphlib.TopologicalSorter. Its dictionary maps each vertex to its predecessors, which reverses the adjacency convention used above. Convert the edges before passing this graph to the library.

from graphlib import TopologicalSorter
predecessors = {vertex: [] for vertex in graph}
for prerequisite, dependents in graph.items():
for dependent in dependents:
predecessors[dependent].append(prerequisite)
library_order = list(TopologicalSorter(predecessors).static_order())
print("Library dependency order:", library_order)
library_positions = {
vertex: index for index, vertex in enumerate(library_order)
}
assert set(library_order) == set(graph)
for prerequisite, dependents in graph.items():
for dependent in dependents:
assert library_positions[prerequisite] < library_positions[dependent]
Library dependency order: ['reads', 'reference', 'metadata', 'align', 'count', 'report']

static_order() yields one valid order and raises CycleError if a cycle prevents completion. Test that every edge points forward instead of requiring one specific ordering when the problem permits several answers.

Course Schedule asks whether all courses can finish. Translate each prerequisite pair into a directed edge, then compare the emitted count with the course count.

Course Schedule II also requests a valid order. Include isolated courses and explain what you return when a cycle blocks completion.

Download the Python source to run the complete example locally.

Kahn, 1962 presents a method for ordering large networks by their dependencies.

Python’s graphlib documentation defines the predecessor representation and cycle exceptions. Its incremental interface also separates ready tasks from tasks that have finished.

MIT’s graph lecture notes include a lecture on DFS and topological order. Compare that approach with the indegree invariant used here.

Python’s deque documentation describes efficient operations at both ends of the queue. Those operations avoid the reference shifts that list.pop(0) requires.