Sub topic 4
Why Only DAGs Have Topological Orders
This chapter assumes you know the definition of a topological order from the previous chapter. It also assumes basic Python, adjacency lists, and proof by contradiction and induction at the level of an introductory discrete math course.
A topological order of a directed graph is a sequence that lists every vertex exactly once, such that for every edge u -> v, u appears before v. The central fact about topological orders is this theorem:
Theorem. A finite directed graph has a topological order if and only if it contains no directed cycle.
The theorem tells you what to expect from any topological sort algorithm. If the input is a DAG, a valid order always exists and the algorithm should find it. If the input has a cycle, no order exists, and the algorithm should report the cycle instead of returning something incorrect. The proofs of both directions also lead directly to the two standard algorithms in the next chapters.
The Structure of the Argument
The proof has two directions, and the second needs a small lemma.
Direction 1: A Cycle Rules Out Any Order
Suppose the graph has a directed cycle v1 -> v2 -> ... -> vk -> v1, and suppose, for contradiction, that some topological order exists. Write pos(x) for the index of vertex x in that order.
Every edge must point forward in the order, so each edge on the cycle gives a strict inequality:
v1 -> v2givespos(v1) < pos(v2)v2 -> v3givespos(v2) < pos(v3)- continuing around the cycle,
vk -> v1givespos(vk) < pos(v1)
Chaining these gives pos(v1) < pos(v1), which is impossible. So no topological order exists.
The argument works for a cycle of any length:
| Cycle length | Example | Why it fails |
|---|---|---|
| 1 (self-loop) | `a -> a` | needs `pos(a) < pos(a)` |
| 2 | `a -> b -> a` | needs `a` before `b` and `b` before `a` |
| k | `v1 -> ... -> vk -> v1` | the inequalities chain into `pos(v1) < pos(v1)` |
The Lemma: Every Finite DAG Has a Source
A source is a vertex with in-degree 0, meaning no edges point into it.
Lemma. Every nonempty finite DAG has at least one source.
Proof. Pick any vertex x0. If it has no incoming edge, it is a source and we are done. Otherwise, choose an edge x1 -> x0 and move to x1. Repeat: as long as the current vertex has a predecessor, step backward to one.
If this backward walk never finds a source, it continues forever. The graph has only n vertices, so after at most n steps some vertex repeats. Say xi = xj with i < j. The walk then contains edges xj -> x(j-1) -> ... -> xi, and because xj = xi, those edges form a directed cycle. That contradicts the assumption that the graph is acyclic. So the walk must stop, and it stops at a source.
A symmetric argument walks forward along outgoing edges and shows that every finite DAG also has a sink, a vertex with out-degree 0. The DFS-based algorithm later in this tutorial relies on that version: the first vertex DFS finishes is always one with no unfinished successors.
Direction 2: Every DAG Has an Order
Proof by induction on the number of vertices n.
- Base case. If
n = 0, the empty sequence is a valid topological order, because there are no edges to violate. - Inductive step. Let
Gbe a DAG withn >= 1vertices. By the lemma,Ghas a sources. Removesand its outgoing edges to getG'. Deleting vertices cannot create a cycle, soG'is a DAG withn - 1vertices. By the induction hypothesis,G'has a topological orderL'. Now takeL = [s] + L'.
Check that L is valid. Every edge of G' points forward within L', so it also points forward in L. Every remaining edge starts at s, which is first in L, so those edges point forward too. No edge points into s, because s is a source. Therefore L is a topological order of G.
This proof is constructive: it describes how to build the order. Repeatedly finding and removing a source is the core of Kahn's algorithm. Kahn's algorithm adds in-degree counters and a queue so it never searches for sources from scratch.
Turning the Proof into Code
The function below follows the proof directly, with no optimization. On each round it scans the remaining vertices for a source. If it finds none, the lemma's backward walk must find a cycle, so the function returns that cycle as evidence. Either way, the caller gets a certificate: a valid order or a concrete cycle.
def order_or_cycle(graph):
"""graph maps each node to a list of successors (u -> v means u before v).
Returns ("order", list_of_nodes) if the graph is a DAG,
or ("cycle", list_of_nodes) where consecutive nodes are joined by edges
and the last node has an edge back to the first.
"""
nodes = set(graph)
for u in graph:
nodes.update(graph[u])
preds = {u: set() for u in nodes}
for u in graph:
for v in graph[u]:
preds[v].add(u)
remaining = set(nodes)
order = []
while remaining:
# A source of the remaining subgraph has no predecessors left in it.
sources = [u for u in remaining if not (preds[u] & remaining)]
if not sources:
return ("cycle", find_cycle_backwards(preds, remaining))
s = min(sources) # min() only makes the output deterministic
order.append(s)
remaining.remove(s)
return ("order", order)
def find_cycle_backwards(preds, remaining):
"""Walk backward along predecessor edges until a vertex repeats."""
u = min(remaining)
path = [u]
index = {u: 0}
while True:
# Every remaining vertex has a remaining predecessor, so this succeeds.
u = min(p for p in preds[u] if p in remaining)
if u in index:
cycle = path[index[u]:]
cycle.reverse() # the walk went backward; flip it to follow edges
return cycle
index[u] = len(path)
path.append(u)
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
print(order_or_cycle(courses))
# ('order', ['intro', 'data_structures', 'discrete_math', 'algorithms'])
tangled = {"start": ["a"], "a": ["b"], "b": ["c"], "c": ["a", "d"], "d": []}
print(order_or_cycle(tangled))
# ('cycle', ['b', 'c', 'a'])In the second example, start is removed first because it is a source. After that, a, b, c, and d each still have a predecessor among the remaining vertices, so no source exists. The backward walk from a visits c, then b, then returns to a. Reversed, the walk gives the cycle b -> c -> a -> b. Vertex d is not on the cycle. It is blocked only because it depends on c.
This version rescans every remaining vertex on each round, so it takes roughly O(V · (V + E)) time. That is acceptable for a proof sketch but not for real use. The next two chapters bring the cost down to O(V + E).
Edge Cases the Theorem Covers
| Situation | Order exists? | Notes |
|---|---|---|
| Empty graph | Yes | The empty list is valid |
| Vertices with no edges | Yes | Any permutation is valid |
| Disconnected DAG | Yes | Each component is ordered, and the components can be interleaved |
| Duplicate edges `u -> v` twice | Yes, if acyclic | The duplicates add the same constraint twice |
| Self-loop `u -> u` | No | A cycle of length 1 |
| Cycle in one component only | No | One cycle blocks the whole order |
The last row matters in practice. A single cycle anywhere in the graph means no complete order exists, even if the rest of the graph is a clean DAG. Some tools work around this by ordering everything outside the cycle and reporting the vertices they could not place. In the example above, those vertices are a, b, c, and d.
Common Mistakes
- Treating an undirected cycle as a problem. The edges
a -> b,a -> c,b -> d,c -> dform a loop if you ignore direction, but they contain no directed cycle. This "diamond" is a DAG with valid orders such asa, b, c, d. - Assuming a source must be reachable from everything. A DAG can have several sources, and they need not be connected to each other.
- Forgetting vertices that appear only as edge targets. If
algorithmsappears in a successor list but not as a key, it is still a vertex. The code above collects such vertices explicitly.
Exercise
The graph has edges x -> y, y -> z, z -> w, and w -> y. Show directly, using positions, that it has no topological order, and say which vertices the source-removal process places before it gets stuck.
Show answer
The cycle y -> z -> w -> y requires pos(y) < pos(z) < pos(w) < pos(y), which is a contradiction. Source removal places only x, because x is the only vertex with in-degree 0. After x is removed, y, z, and w each still have a remaining predecessor (w, y, and z respectively), so no source remains.
Exercise
Prove that every nonempty finite DAG has a sink (a vertex with out-degree 0).
Show answer
Start at any vertex and repeatedly follow an outgoing edge. If you never reach a vertex with no outgoing edge, then after at most n steps some vertex repeats, and the edges walked between its two visits form a directed cycle, which contradicts acyclicity. So the walk ends at a vertex with out-degree 0.
Exercise
A colleague says that deleting a source from a DAG might create a cycle in what remains, which would break the induction. Is that right?
Show answer
No. Every cycle in the smaller graph uses only vertices and edges that were already in the original graph, so it would also be a cycle in the original DAG. Deleting vertices or edges can never create a cycle, so the remaining graph is still a DAG.