Sub topic 17
Topological sort of a DAG
A topological sort lists the vertices of a directed graph so that every edge points forward in the list. This chapter assumes you know BFS and DFS, the adjacency-list representation, and DFS edge types (tree, back, forward, cross). GATE questions on this topic ask for a valid order, the number of valid orders, or whether an order exists at all.
What the problem asks
Take a directed graph with edge u -> v. A topological order puts u before v for every such edge. Typical uses are build systems, course prerequisites, and spreadsheet cell dependencies.
An order exists if and only if the graph is a DAG (directed acyclic graph). A cycle makes the order impossible, because each vertex on the cycle would have to come before itself.
Valid orders for this graph are 0 1 2 3 4 and 0 2 1 3 4. Vertex 0 must come first and vertex 3 must follow both 1 and 2. Only the relative order of 1 and 2 is free.
Method 1: Kahn's algorithm (in-degree peeling)
The in-degree of a vertex is the number of edges entering it. A vertex with in-degree 0 has no unmet dependencies, so it can go next.
- Compute the in-degree of every vertex.
- Put all in-degree-0 vertices in a queue.
- Remove a vertex from the queue and append it to the output. For each outgoing edge
u -> v, decreaseindeg[v]. If it reaches 0, enqueuev. - If the output has fewer than V vertices, the graph has a cycle.
from collections import deque
def topo_kahn(n, edges):
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
queue = deque(u for u in range(n) if indeg[u] == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
queue.append(v)
return order if len(order) == n else None
edges = [(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)]
print(topo_kahn(5, edges)) # [0, 1, 2, 3, 4]
print(topo_kahn(3, [(0, 1), (1, 2), (2, 1)])) # None (cycle 1 -> 2 -> 1)Each vertex is enqueued once and each edge is examined once, so the time is O(V + E) with an adjacency list.
Method 2: DFS and reversed finishing order
Run DFS over the whole graph. Append each vertex to a list at the moment it finishes (all its descendants are done). Reverse the list at the end.
The reason it works: in a DAG, for any edge u -> v, DFS finishes v before it finishes u. A DAG has no back edges, so v is either unvisited (it becomes a descendant of u) or already finished. Either way v finishes first, so u appears before v after the reversal.
def topo_dfs(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
state = [0] * n # 0 = unvisited, 1 = on the current path, 2 = finished
finished = []
def visit(u):
state[u] = 1
for v in adj[u]:
if state[v] == 1:
raise ValueError("cycle detected")
if state[v] == 0:
visit(v)
state[u] = 2
finished.append(u)
for u in range(n):
if state[u] == 0:
visit(u)
return finished[::-1]
print(topo_dfs(5, [(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)])) # [0, 2, 1, 3, 4]The trace on the chapter's graph finishes the vertices in the order 4, 3, 1, 2, 0. Reversed, that gives 0 2 1 3 4. The result differs from Kahn's output, and both are valid.
Comparing the two methods
| Property | Kahn's algorithm | DFS-based |
|---|---|---|
| Time | O(V + E) | O(V + E) |
| Extra space | In-degree array and queue | Recursion stack and state array |
| Cycle detection | Output has fewer than V vertices | Back edge found |
| Order produced | Front to back, level by level | Built in reverse as vertices finish |
| Recursion depth risk | None | Up to V frames on a long chain |
Edge cases and variations
- Multiple valid orders. Whenever the queue holds more than one vertex, any of them can come next. The number of valid orders is the number of such choices summed over all paths. For small GATE graphs, count by placing forced vertices first.
- Unique order. The order is unique if and only if the queue never holds more than one vertex in Kahn's algorithm. This is equivalent to the DAG having a Hamiltonian path.
- Lexicographically smallest order. Replace the queue with a min-heap. The time becomes O((V + E) log V) because of the heap operations.
- Disconnected graphs. Kahn's algorithm handles them naturally. In DFS, the outer loop over all vertices is what covers every component.
- Self-loops and duplicate edges. A self-loop is a cycle. Duplicate edges are harmless as long as the in-degree counts each copy, as the code above does.
- Longest path in a DAG. Process vertices in topological order and relax each outgoing edge. This takes O(V + E) and also works with negative weights, because no cycles exist.
Common errors
- Starting Kahn's algorithm with the wrong set. Only in-degree-0 vertices belong in the initial queue.
- Forgetting the length check at the end of Kahn's algorithm. Without it, a cyclic graph silently returns a partial order.
- Calling a cross or forward edge a cycle in the DFS version. Only a back edge indicates a cycle.
- Assuming the answer is unique. Exam options often list several valid orders. Check each candidate by testing every edge.
Exercise
Kahn's algorithm runs on a directed graph with 6 vertices and outputs only 4 of them. What does this tell you, and what is the largest number of the remaining vertices that could lie outside any cycle?
Show answer
The graph contains a cycle, so no topological order exists. The 2 vertices never output each have an unprocessed predecessor. They are either on a cycle or reachable from one. At least one cycle lies among the 2 left-over vertices or involves them, so at most 1 left-over vertex can be off every cycle (it would then be downstream of a cycle).
Exercise
How many valid topological orders does the graph with edges 0->1, 0->2, 1->3, 2->3, 3->4 have?
Show answer
2. Vertex 0 is forced first. Vertices 1 and 2 can appear in either order, then 3 and 4 follow in forced positions. The orders are 0 1 2 3 4 and 0 2 1 3 4.