Sub topic 3
What a Topological Order Is
This chapter assumes you can read basic Python, know what directed edges and adjacency lists are, and understand Big-O notation. The previous chapters showed how to model dependencies as a directed graph and what makes a graph acyclic. This chapter defines the object every later chapter computes: a topological order. It also shows how to check whether a given sequence is one.
The Definition
Take a directed graph G with vertex set V and edge set E. A topological order of G is a sequence that lists every vertex exactly once, such that for every edge u → v, u appears before v.
The definition has two parts, and a sequence must satisfy both:
- Coverage. Every vertex appears exactly once. No vertex is missing and none is repeated.
- Edge ordering. For every edge u → v, the position of u is less than the position of v.
A useful way to picture it: write the vertices on a horizontal line in the chosen order. The sequence is a topological order exactly when every edge points to the right.
Throughout this tutorial, the edge u → v means "u must come before v". In a course catalog, that reads "u is a prerequisite of v". In a build system, it reads "u must be built before v".
A Worked Example
Here is the course graph used across the tutorial:
The graph has four edges, so a valid order must satisfy four constraints:
- intro before data_structures
- intro before discrete_math
- data_structures before algorithms
- discrete_math before algorithms
The table checks several candidate sequences against these constraints.
| Candidate sequence | Valid? | Reason |
|---|---|---|
| intro, data_structures, discrete_math, algorithms | Yes | All four edges point forward |
| intro, discrete_math, data_structures, algorithms | Yes | All four edges point forward |
| data_structures, intro, discrete_math, algorithms | No | Edge intro → data_structures points backward |
| intro, data_structures, algorithms, discrete_math | No | Edge discrete_math → algorithms points backward |
| intro, data_structures, discrete_math | No | algorithms is missing |
| intro, intro, data_structures, discrete_math, algorithms | No | intro appears twice |
The first two rows are both valid. datastructures and discretemath have no edge between them, so the definition says nothing about their relative order. A later chapter covers when the order is unique and how to count the alternatives. For now, the point is that "a topological order" means any sequence that satisfies the constraints. It does not mean one specific sequence.
Laying the Order on a Line
Drawing the graph with its vertices in topological order makes the "all edges point right" property visible:
Diagram: Four nodes in a row from left to right: intro, data_structures, discrete_math, algorithms. Arrows go from intro to data_structures, intro to discrete_math, data_structures to algorithms, and discrete_math to algorithms. All arrows point to the right.
The invisible links (~~~) only fix the left-to-right placement. They are not dependencies.
Equivalent Ways to State the Condition
The definition has several equivalent forms. Each one is useful in a different situation.
- Edge form. For every edge u → v, pos(u) < pos(v). This form is the easiest to check in code.
- Predecessor form. Each vertex appears after all of its direct predecessors. Build tools and Python's
graphlibdescribe dependencies this way. - Path form. If there is any directed path from u to v, then pos(u) < pos(v).
The path form follows from the edge form. Take a path u → w₁ → w₂ → … → v. Each edge on the path moves strictly to the right, so the whole path does too. You therefore only need to check direct edges. If intro comes before discretemath and discretemath comes before algorithms, then intro automatically comes before algorithms. Nobody has to list that transitive constraint.
Checking a Sequence in Code
Verifying a proposed order is cheaper and simpler than computing one. It also makes a good test oracle for the sorting algorithms in the next chapters. The checker below covers both parts of the definition and reports every edge that points backward.
def collect_nodes(graph):
"""Return every node, including nodes that appear only as edge targets."""
nodes = set(graph)
for targets in graph.values():
nodes.update(targets)
return nodes
def check_topological_order(graph, order):
"""graph maps u to the list of v with an edge u -> v.
Returns (ok, problems), where problems is a list of strings
describing each violation.
"""
problems = []
nodes = collect_nodes(graph)
# Coverage: every node exactly once.
seen = set()
for node in order:
if node in seen:
problems.append(f"duplicate node: {node!r}")
elif node not in nodes:
problems.append(f"unknown node: {node!r}")
seen.add(node)
for node in sorted(nodes - seen, key=repr):
problems.append(f"missing node: {node!r}")
if problems:
return False, problems
# Edge ordering: every edge must point forward.
position = {node: i for i, node in enumerate(order)}
for u, targets in graph.items():
for v in targets:
if position[u] >= position[v]:
problems.append(f"edge {u!r} -> {v!r} points backward")
return not problems, problems
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
candidates = [
["intro", "data_structures", "discrete_math", "algorithms"],
["intro", "discrete_math", "data_structures", "algorithms"],
["data_structures", "intro", "discrete_math", "algorithms"],
["intro", "data_structures", "discrete_math"],
]
for seq in candidates:
print(check_topological_order(courses, seq))Output:
(True, [])
(True, [])
(False, ["edge 'intro' -> 'data_structures' points backward"])
(False, ["missing node: 'algorithms'"])The checker returns before the edge loop if coverage fails. When a node is missing, position[v] would raise a KeyError, and a coverage failure already settles the answer.
The checker runs in O(V + E) time. Building the node set and the position map takes O(V + E). The edge loop visits each edge once and does an O(1) dictionary lookup per edge.
Edge Cases
Some inputs show what the definition means at its boundaries.
| Input | Topological order? |
|---|---|
| Empty graph `{}` | The empty sequence is valid |
| Single node, no edges | The one-element sequence is valid |
| Isolated nodes, no edges at all | Every permutation is valid |
| Self-loop `{"a": ["a"]}` | None exists, since pos(a) < pos(a) is impossible |
| Two-node cycle `a → b → a` | None exists |
| Duplicate edge listed twice | Same constraint twice; the duplicate changes nothing |
| Disconnected components | Valid orders can interleave the components freely |
The cycle rows preview the next chapter. When a cycle exists, no sequence can satisfy every edge. The next chapter proves the converse: every acyclic graph has at least one topological order.
Common Errors
Other frequent mistakes:
- Dropping target-only nodes. If a node appears only as an edge target and never as a dictionary key, code that iterates
graph.keys()misses it.collect_nodeshandles this case. The algorithms in later chapters handle it withindegree.get(v, 0). - Checking only adjacent pairs. Some people check only that consecutive elements in the sequence are connected or unordered. That test is wrong. An edge can connect two vertices that sit far apart in the sequence, so you must check every edge.
- Confusing "topological order" with "BFS order". A breadth-first traversal from a source can visit a vertex before one of its other predecessors. In the graph
a → b,a → c,c → b, BFS fromamay visitbbeforec, which breaks the edgec → b. - Expecting one canonical answer. Tests that compare against a single hard-coded list break when an equally valid order comes back. Test against a checker like the one above, or define a tie-breaking rule. A later chapter uses the lexicographically smallest order as that rule.
A Useful Symmetry
Reverse every edge of G to get the reverse graph Gᴿ. If a sequence is a topological order of G, then reading it backward gives a topological order of Gᴿ. Each edge u → v in G becomes v → u in Gᴿ, and reversing the sequence turns "u before v" into "v before u". The DFS-based algorithm later in this tutorial relies on this kind of reversal.
Exercise
For the graph {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}, which of these sequences are topological orders: (1) a, c, b, d (2) a, b, d, c (3) c, a, b, d?
Show answer
Only (1). Sequence (2) places d before c, which breaks the edge c -> d. Sequence (3) places c before a, which breaks the edge a -> c. Sequence (1) satisfies all four edges: a -> b, a -> c, b -> d, and c -> d.
Exercise
A teammate's checker verifies only that pos(u) < pos(v) for every edge u -> v, using position = {n: i for i, n in enumerate(order)}. Give an input where it wrongly accepts a sequence.
Show answer
Repeat a node. For the graph {"a": ["b"], "b": []} and the order ["b", "a", "b"], the dictionary keeps the last position of b, which is 2. The check pos(a)=1 < pos(b)=2 passes, but b appears twice and once before a. The checker must also confirm that every node appears exactly once.
Exercise
The graph {"x": ["y"], "y": ["z"]} has edges x -> y and y -> z only. Explain why a valid order must place x before z even though no edge connects them directly.
Show answer
The path x -> y -> z exists. The edge constraints force pos(x) < pos(y) and pos(y) < pos(z), so pos(x) < pos(z) by transitivity. Checking direct edges is enough, because every path constraint follows from them.