Sub topic 8
Running Time and Memory
This chapter assumes you know Big-O notation and the adjacency list representation, and that you have read the earlier chapters on Kahn's algorithm and DFS-based topological sort. Throughout, V is the number of nodes and E is the number of edges.
Why both algorithms are O(V + E)
Both algorithms touch each node a constant number of times and each edge a constant number of times. That gives linear time in the size of the graph.
Kahn's algorithm
The work splits into three parts:
- Computing in-degrees. The loop visits every node once and every edge once, which costs O(V + E).
- Queue operations. A node enters the queue only when its in-degree reaches zero. That happens at most once per node, so the queue does O(V) pushes and pops in total.
- Edge relaxation. When a node is dequeued, the algorithm decrements the in-degree of each of its successors. Every edge is handled exactly once over the whole run, which costs O(E).
The total is O(V + E). The final cycle check, len(order) != len(indegree), takes O(1).
DFS-based sort
Each node turns GRAY once and BLACK once, so the algorithm makes O(V) calls to visit. Inside a call, it scans the node's adjacency list once, so the scans add up to O(E) across all calls. Reversing the finishing order costs O(V). The total is again O(V + E).
Memory
| Structure | Kahn's algorithm | DFS-based sort |
|---|---|---|
| Graph (adjacency list) | O(V + E) | O(V + E) |
| Per-node bookkeeping | `indegree` dict, O(V) | `color` dict, O(V) |
| Pending work | queue, up to O(V) | recursion stack, up to O(V) |
| Output | `order`, O(V) | `order`, O(V) |
Both algorithms need O(V) extra space on top of the graph. The difference lies in where that space lives. Kahn's queue sits on the heap, which can grow as large as available memory. The DFS stack is the Python call stack, and CPython limits its depth to 1000 frames by default.
The following script builds a chain of 5000 nodes. Kahn's algorithm sorts it. The recursive DFS fails on it.
from collections import deque
import sys
def chain(n):
return {i: [i + 1] if i + 1 < n else [] for i in range(n)}
def dfs_order(graph):
seen, order = set(), []
def visit(u):
seen.add(u)
for v in graph[u]:
if v not in seen:
visit(v)
order.append(u)
for u in graph:
if u not in seen:
visit(u)
return order[::-1]
def kahn_order(graph):
indeg = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indeg[v] += 1
q = deque(u for u in graph if indeg[u] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in graph[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order
g = chain(5000)
print(len(kahn_order(g)))
try:
dfs_order(g)
except RecursionError:
print("DFS hit the recursion limit", sys.getrecursionlimit())
# 5000
# DFS hit the recursion limit 1000Common mistakes that break linear time
The algorithms are linear only when every step inside them costs O(1). These implementation choices quietly make them slower:
- Using
list.pop(0)as the queue. Each pop shifts the whole list, so Kahn's algorithm becomes O(V² + E). Usecollections.dequeandpopleft(). - Checking
v in orderon a list. Each membership test scans the list, which adds O(V) per check. Track visited nodes in a set or dict. - Rescanning for zero in-degree nodes. Some naive versions search the whole graph for a source node on every step, which costs O(V · (V + E)). Kahn's algorithm avoids this by pushing nodes onto the queue at the moment their in-degree hits zero.
- Using an adjacency matrix. Listing the successors of a node costs O(V) no matter how many edges it has, so the sort becomes O(V²). This is fine for dense graphs and wasteful for sparse ones.
Exercise
A colleague writes Kahn's algorithm with a plain list as the queue and removes items with queue.pop(0). What is the running time on a graph with V nodes and E edges, and what one-line change restores O(V + E)?
Show answer
Each pop(0) shifts the remaining items and costs O(V). With V pops the total is O(V² + E). Using queue = deque(...) with queue.popleft() makes each pop O(1), so the algorithm runs in O(V + E) again.
Exercise
You need to sort a build graph with 200,000 targets, where some dependency chains are 50,000 links long. Which algorithm should you choose, and why?
Show answer
Choose Kahn's algorithm, or a DFS that uses an explicit stack. Both run in O(V + E) time, but recursive DFS needs one call frame per link in a chain. A 50,000-link chain exceeds Python's default recursion limit of 1000, so recursive DFS raises RecursionError. Kahn's queue lives on the heap and has no such limit.