Sub topic 5
Why Traversal Runs in O(V + E)
This chapter assumes you have read the BFS and iterative DFS labeling chapters and know Big-O notation. Here V is the number of vertices and E is the number of edges. The goal is to explain why both labeling methods cost O(V + E) time and space, and which small coding mistakes quietly make them slower.
Counting the Work
Traversal-based labeling does three kinds of work:
- Building the adjacency list. Creating
nempty lists costs O(V). Each edge(u, v)appends to two lists, which costs O(E) in total. - The outer loop.
for start in range(n)visits each vertex once and does constant work when the vertex already has a label. That costs O(V). - The inner traversal. A vertex gets its label at the moment it is pushed or enqueued, so it enters the queue or stack at most once. Each vertex is therefore popped once, and its adjacency list is scanned once.
The total length of all adjacency lists in an undirected graph is exactly 2E, because every edge appears in both endpoints' lists. Summed across all components, the inner loops do V pops and 2E neighbor checks. Adding the three parts gives O(V) + O(E) + O(V + 2E) = O(V + E).
Measuring It Directly
The version below adds counters to the BFS labeler so you can see the bound for yourself.
from collections import deque
def count_work(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
label = [-1] * n
pops = 0
scans = 0
count = 0
for start in range(n):
if label[start] != -1:
continue
label[start] = count
queue = deque([start])
while queue:
u = queue.popleft()
pops += 1
for v in adj[u]:
scans += 1
if label[v] == -1:
label[v] = count
queue.append(v)
count += 1
return pops, scans
print(count_work(6, [(0, 1), (1, 2), (3, 4)]))
# (6, 6)
print(count_work(5, [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2)]))
# (5, 10)The pop count always equals V and the scan count always equals 2E, however the edges are grouped into components.
Why Both Terms Matter
Neither term can be dropped. A graph with a million isolated vertices has E = 0, but the outer loop still runs a million times. A dense graph has E close to V²/2, so the edge scans dominate. Writing O(V + E) covers both cases.
Space
| Structure | Size |
|---|---|
| Adjacency list | O(V + E) |
| `label` or `seen` array | O(V) |
| Queue or stack | O(V) at most |
| Total | O(V + E) |
The queue or stack stays at O(V) only because vertices are marked when they are pushed.
Mistakes That Break the Bound
- Using
list.pop(0)as a queue. Each call shifts every remaining element, which can make BFS O(V²). Usecollections.deque. - Checking
v in visitedon a list. Each membership test costs O(V). Use a boolean array or a set. - Marking on pop instead of on push. A vertex can then be pushed once for each of its neighbors. Time stays O(V + E), but the stack can grow to O(E).
- Using an adjacency matrix. Scanning a row costs O(V) whether or not the edges exist, so the total becomes O(V²).
Exercises
Exercise
A BFS labeler uses a plain Python list and calls queue.pop(0). What is its worst-case time on a graph whose single component contains every vertex, and why?
Show answer
O(V² + E). Each pop(0) shifts the remaining elements, which costs up to O(V), and it runs V times. Using deque.popleft() makes each pop O(1) and restores O(V + E).
Exercise
In count_work, the edge list contains (2, 2), a self-loop, plus the parallel edges (0, 1) and (0, 1). How do pops and scans change compared with the graph without these extra edges?
Show answer
Pops do not change, because each vertex is still enqueued once. Scans rise by 2 for each added edge entry: the self-loop appends 2 to adj[2] twice, and each copy of (0, 1) adds one entry to each endpoint's list. Scans still equal 2E, where E counts every edge in the input list.