Sub topic 3
What a Topological Order Is
This chapter assumes you know basic Python, can read an adjacency list, and are comfortable with directed edges. Earlier chapters covered modeling dependencies as directed graphs and what makes a graph acyclic. Here we define the ordering that the rest of the tutorial computes.
The Definition
A topological order of a directed graph is a list of all its vertices in which every edge points forward. Formally, for every edge u -> v, vertex u appears before vertex v in the list.
In this tutorial, u -> v means "u must come before v". In a course catalog, intro -> algorithms means you take intro before algorithms.
The definition has two parts, and a list must satisfy both:
- Completeness. Every vertex appears exactly once. A list that leaves out a vertex or repeats one is not a topological order.
- Edge consistency. No edge points backward from a later position to an earlier one.
The definition puts no constraint on vertices that have no path between them. Their relative order is free.
A Worked Example
Take four courses with these prerequisites:
The table below checks some candidate lists.
| Candidate order | Valid? | Reason |
|---|---|---|
| intro, data_structures, discrete_math, algorithms | Yes | Every edge points forward |
| intro, discrete_math, data_structures, algorithms | Yes | The two middle courses have no edge between them |
| data_structures, intro, discrete_math, algorithms | No | Edge `intro -> data_structures` points backward |
| intro, data_structures, algorithms | No | `discrete_math` is missing |
The first two rows show that one graph can have several valid orders. A later chapter covers when the order is unique.
Checking a Candidate Order
To check a list, record each vertex's position, then confirm that every edge goes from a smaller position to a larger one.
def is_topological_order(graph, order):
"""graph maps each node to the nodes that must come after it."""
nodes = set(graph)
for targets in graph.values():
nodes.update(targets)
# Completeness: every node exactly once.
if len(order) != len(nodes) or set(order) != nodes:
return False
position = {node: i for i, node in enumerate(order)}
# Edge consistency: every edge points forward.
for u, targets in graph.items():
for v in targets:
if position[u] >= position[v]:
return False
return True
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
print(is_topological_order(courses, ["intro", "data_structures", "discrete_math", "algorithms"])) # True
print(is_topological_order(courses, ["intro", "discrete_math", "data_structures", "algorithms"])) # True
print(is_topological_order(courses, ["data_structures", "intro", "discrete_math", "algorithms"])) # False
print(is_topological_order(courses, ["intro", "data_structures", "algorithms"])) # FalseThe checker runs in O(V + E) time. It builds the position map once, and each edge lookup takes constant time on average.
Common Errors
- Reversed edge direction. Some code stores "u depends on v" as
u -> v, which is the opposite of the convention used here. Under that convention a valid order is the reverse of the list you expect. Decide on one direction and document it. - Forgetting sink-only nodes. A node that appears only as an edge target, never as a dictionary key, is still a vertex. The checker above collects targets for this reason.
- Checking only adjacent pairs. Confirming that each consecutive pair in the list is fine is not enough. You must test every edge, including edges that skip several positions.
Exercise
The graph has edges a -> b, a -> c, c -> b, and b -> d. Is [a, b, c, d] a topological order? If not, give a valid one.
Show answer
No. The edge c -> b requires c before b, but b comes first. The only valid order is [a, c, b, d].
Exercise
A graph has three vertices x, y, z and no edges. How many topological orders does it have?
Show answer
Six. With no edges there are no constraints, so every permutation of the three vertices is valid (3! = 6).