Sub topic 8
Running Time and Memory
This chapter assumes you already know Kahn's algorithm and the DFS-based topological sort from the earlier chapters. You should also be comfortable with Big-O notation, adjacency lists, and Python's collections.deque. Here we count the work each algorithm does and the memory it uses. We also look at the implementation mistakes that turn a linear-time sort into a slow one.
Throughout, V is the number of vertices (nodes) and E is the number of directed edges.
The Headline Result
Both Kahn's algorithm and DFS-based topological sort run in O(V + E) time and use O(V) extra memory beyond the graph. An algorithm cannot do better in general, because it has to look at every node to place it and at every edge to respect it. A sort that skipped an edge could put that edge's endpoints in the wrong order.
| Algorithm | Time | Extra memory | Main memory consumers |
|---|---|---|---|
| Kahn's (queue) | O(V + E) | O(V) | in-degree map, queue, output list |
| DFS (recursive) | O(V + E) | O(V) | color map, call stack, output list |
| DFS (explicit stack) | O(V + E) | O(V) | color map, stack of iterators, output list |
| Kahn's with min-heap | O(V log V + E) | O(V) | in-degree map, heap, output list |
The graph itself takes O(V + E) memory as an adjacency list. That is input, so we usually leave it out of the "extra" column.
Counting the Work in Kahn's Algorithm
Kahn's algorithm has three phases. To analyze it, charge each operation to the node or edge that caused it.
- Computing in-degrees. The outer loop runs once per node and the inner loop runs once per outgoing edge. Summed over all nodes, the inner loop runs exactly E times. Cost: O(V + E).
- Seeding the queue. One pass over the in-degree map. Cost: O(V).
- Main loop. A node enters the queue only when its in-degree drops to zero. That happens once at most, because in-degrees only go down. So each node is dequeued once at most. When node
uis dequeued, its outgoing edges are scanned once, and each scan does a constant-time decrement. Over the whole run that adds up to E decrements. Cost: O(V + E).
The final check len(order) != len(indegree) is O(1). Adding the phases gives O(V + E).
This analysis depends on two constant-time assumptions. Dictionary lookups and updates must be O(1). That holds on average for hashable node labels like strings and integers. Queue pushes and pops must also be O(1), which holds for deque.append and deque.popleft.
Counting the Work in DFS
The DFS version uses the same accounting. visit(u) is called only on WHITE nodes, and it colors the node GRAY right away, so it runs once per node. Inside visit(u), the loop over graph[u] runs once per outgoing edge of u. Over all calls that is E iterations, each doing a dictionary lookup and a comparison. The outer for u in graph loop adds O(V). Appending to order is amortized O(1), and the final reverse() is O(V). The total is again O(V + E).
Where the Memory Goes
Kahn's algorithm stores one in-degree counter per node, and the queue holds at most V nodes. A star graph, with one root pointing to V − 1 leaves, puts nearly every node in the queue at once. The output list holds V entries. That is O(V) in total.
DFS stores one color per node and the output list. Its hidden cost is the call stack. In a recursive implementation, the recursion depth equals the length of the longest path DFS follows, and a simple chain of V nodes forces depth V. Each frame stores the current node and a loop position, so the stack is O(V). The asymptotic bound is fine. The practical limit is the problem.
DFS Without Recursion
To remove the recursion limit, keep your own stack of (node, iterator) pairs. The iterator remembers how far you got through a node's neighbors, which is the job the call frame did before. When the iterator runs out, the node is finished.
def topo_sort_dfs_iterative(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color = {}
order = []
for start in graph:
if color.get(start, WHITE) != WHITE:
continue
color[start] = GRAY
stack = [(start, iter(graph.get(start, [])))]
while stack:
u, neighbors = stack[-1]
for v in neighbors:
c = color.get(v, WHITE)
if c == GRAY:
raise ValueError("graph has a cycle")
if c == WHITE:
color[v] = GRAY
stack.append((v, iter(graph.get(v, []))))
break
else:
stack.pop()
color[u] = BLACK
order.append(u)
order.reverse()
return order
n = 100_000
chain = {i: [i + 1] for i in range(n - 1)}
chain[n - 1] = []
result = topo_sort_dfs_iterative(chain)
print(result[:3], result[-3:])
# [0, 1, 2] [99997, 99998, 99999]Each edge is still pulled from an iterator exactly once, because the for loop resumes the same iterator the next time u is on top of the stack. The time stays O(V + E). The stack now lives on the heap, so its size is limited only by available memory.
Measuring Linear Growth
You can check the O(V + E) claim empirically. The script below builds random DAGs by adding edges only from smaller to larger node numbers. That rule guarantees the graph has no cycles. The script doubles both V and E each round and times Kahn's algorithm.
import random
import time
from collections import deque
def topo_sort_kahn(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
queue = deque(u for u, d in indegree.items() if d == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in graph.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) != len(indegree):
raise ValueError("graph has a cycle")
return order
def random_dag(n, m, seed=0):
rng = random.Random(seed)
graph = {i: [] for i in range(n)}
for _ in range(m):
a, b = rng.sample(range(n), 2)
if a > b:
a, b = b, a
graph[a].append(b)
return graph
for n in [50_000, 100_000, 200_000, 400_000]:
g = random_dag(n, 4 * n)
t0 = time.perf_counter()
topo_sort_kahn(g)
elapsed = time.perf_counter() - t0
print(f"V={n:>7} E={4 * n:>8} {elapsed:.3f} s")The exact times depend on your machine. Each row should take roughly twice as long as the one before it, which is what a linear algorithm does when its input doubles.
Common Ways to Lose Linear Time
A correct algorithm can still run slowly if one step that should be O(1) costs more. These are the most common causes:
| Mistake | Why it hurts | Resulting time | Fix |
|---|---|---|---|
| Using a list as a queue with `list.pop(0)` | Every pop shifts all remaining items | O(V² + E) | `collections.deque.popleft()` |
| Checking `if v in visited_list` | Membership test scans the list | O(V · (V + E)) | Use a `set` or dict |
| Recomputing in-degrees each round | Re-scans all edges per removed node | O(V · (V + E)) | Compute once, then decrement |
| Storing the graph as an adjacency matrix | Finding neighbors scans a full row | O(V²) | Use adjacency lists |
| Picking the "next" source by scanning all nodes | Linear scan per step | O(V²) | Keep sources in a queue |
Edge Cases in the Analysis
- Duplicate edges. If
u -> vappears twice in the list, the in-degree ofvcounts it twice and the algorithm decrements it twice. The result is still correct. E then counts edges with multiplicity, so heavily duplicated input costs more than its distinct edges suggest. - Nodes that appear only as targets. If
vis never a key ingraph, theindegree.get(v, 0)call still registers it.graph.get(u, [])treats it as having no outgoing edges. Without those defaults the code would crash or silently drop nodes. Either way, the node still adds O(1) to the V term. - Many isolated nodes. A graph with a million nodes and no edges still takes O(V) time. The V term in O(V + E) is real work and not a rounding detail.
- Cycles. Stopping on a cycle does not change the bound. Kahn's algorithm stops early and does at most O(V + E) work. DFS raises an error the moment it sees a GRAY neighbor, which also happens within O(V + E).
- Priority-queue variants. Replacing the deque with a binary heap makes each push and pop O(log V). With V of each, the total is O(V log V + E), which is often written as the looser O((V + E) log V). Pay that cost only when you need a specific order among ties.
- Input conversion. If your data arrives as predecessor sets (the format
graphlibuses) and you build a successor map from it, the conversion costs O(V + E) time and doubles the graph's memory. The total is still linear.
Exercise
A colleague's Kahn's implementation stores sources in a Python list, removes the next one with sources.pop(0), and adds new sources with sources.append(v). What is its worst-case running time, and which graph shape triggers it?
Show answer
Each pop(0) shifts every remaining element, so one pop costs O(k) where k is the list's current length. A star graph, with one root pointing to V − 1 leaves, puts about V − 1 items in the list at once. Popping them one by one costs about V²/2 shifts, so the total is O(V² + E). Replacing the list with a deque and using popleft() restores O(V + E).
Exercise
The recursive DFS sort and Kahn's algorithm both use O(V) extra memory. Why does the recursive DFS fail on a 5,000-node chain in CPython while Kahn's algorithm does not?
Show answer
On a chain, the recursive DFS nests one call per node, so the recursion depth reaches 5,000. That exceeds CPython's default limit of about 1,000 frames and raises RecursionError. Kahn's algorithm keeps its state in a deque and a dictionary on the heap and never recurses, so only total memory limits it. The asymptotic bound is the same. What differs is that the DFS uses the limited call stack.
Exercise
A graph has V = 1,000 nodes and E = 400,000 edges. Is O(V + E) meaningfully better than O(V²) here, and would an adjacency matrix be a reasonable representation?
Show answer
V² = 1,000,000, and V + E = 401,000, which is within a small constant factor of V². The graph is dense (40% of all possible ordered pairs), so both bounds describe about the same amount of work. A 1,000 × 1,000 matrix of booleans is small, and scanning rows costs about as much as walking adjacency lists. Either representation is reasonable.