Sub topic 5
Why Traversal Runs in O(V + E)
This chapter assumes you can read the BFS and iterative DFS labeling code from the previous two chapters. It also assumes you know Big-O notation and the difference between a Python list and a collections.deque. We use V for the number of vertices and E for the number of edges throughout.
Both traversal-based labeling methods claim a running time of O(V + E). That bound is easy to state and easy to lose by accident. A single wrong data structure choice can turn a linear algorithm into a quadratic one, and the output still looks correct. This chapter works through the argument step by step so you can check any traversal you write against it.
The Shape of the Argument
A naive reading of BFS gives a loose bound. The outer for loop runs V times. Inside it is a while loop, and inside that is a for loop over neighbors. Three nested loops suggest something like O(V · V · V), or at best O(V²).
That reading is wrong because the loops do not each run their full range on every pass. The right technique is aggregate analysis: instead of multiplying loop bounds, you count how many times each unit of work happens across the whole run.
Two facts carry the whole proof:
- Every vertex enters the queue (or stack) exactly once.
- Every adjacency list is scanned exactly once, when its vertex is removed.
Everything else follows from these two facts.
Counting the Work in BFS
Here is the BFS labeling function again, with counters added for the two kinds of work. Running it shows the counts directly.
from collections import deque
def bfs_work(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
label = [-1] * n
enqueues = 0
scans = 0
count = 0
for start in range(n):
if label[start] != -1:
continue
label[start] = count
queue = deque([start])
enqueues += 1
while queue:
u = queue.popleft()
for v in adj[u]:
scans += 1
if label[v] == -1:
label[v] = count
queue.append(v)
enqueues += 1
count += 1
return enqueues, scans
print(bfs_work(6, [(0, 1), (1, 2), (3, 4)]))
# (6, 6)
# A complete graph on 5 vertices has 10 edges.
k5 = [(i, j) for i in range(5) for j in range(i + 1, 5)]
print(bfs_work(5, k5))
# (5, 20)In both runs the enqueue count equals V and the scan count equals 2E. The structure of the graph doesn't change this. The same thing happens on any input you try.
Fact 1: each vertex is enqueued once
A vertex is appended to the queue only when its label is -1, and it gets a real label in the same step. After that, the check label[v] == -1 fails forever. So no vertex can enter the queue twice. Every vertex enters at least once, because the outer loop starts a new search from any vertex still unlabeled. Total enqueues: exactly V. Each append and popleft on a deque is O(1), so queue operations cost O(V).
Fact 2: each adjacency list is scanned once
The inner for v in adj[u] runs only when u is dequeued, and Fact 1 says that happens once per vertex. So the total number of inner iterations is the sum of all list lengths:
- In an undirected graph, each edge (u, v) is stored twice, once in
adj[u]and once inadj[v]. The sum of degrees is therefore 2E. This is the handshake lemma. - In a directed graph, each edge is stored once, in its source's list, so the sum of out-degrees is E.
Either way the inner loop does O(E) total work, and each iteration does O(1) work: one list index and one comparison.
The remaining pieces
The outer loop runs V times. Most iterations end at the continue, but even a skipped vertex costs one check, so this part is O(V). Building the adjacency list costs O(V) to create the empty lists plus O(E) to append the edges. Adding these up:
O(V) build + O(E) build + O(V) outer loop + O(V) queue ops + O(E) scans = O(V + E)
The Same Argument for Iterative DFS
The iterative DFS from the previous chapter marks seen[v] = True at the moment it pushes v. That is the same invariant BFS uses, so the proof carries over unchanged: V pushes, V pops, and one scan per adjacency list. Python's list.append and list.pop() from the end are both amortized O(1).
The order of visits differs between BFS and DFS, but the cost doesn't. The proof never uses visit order.
Why "V + E" and Not Just "E"
You might expect E to dominate. In a connected graph E ≥ V − 1, so O(V + E) reduces to O(E). Connected-component problems are exactly the case where the graph may not be connected, though. Take a graph with a million isolated vertices and no edges: E = 0, yet the algorithm must still label a million vertices. The V term pays for the outer loop and for the components that consist of a single vertex. Keep both terms in the bound.
Space Complexity
| Structure | Size | Why |
|---|---|---|
| Adjacency list | O(V + E) | V list headers, 2E entries for undirected |
| `label` or `seen` array | O(V) | One slot per vertex |
| Queue or stack | O(V) worst case | Each vertex is in it at most once |
| Result lists (DFS version) | O(V) | Each vertex appears in one component |
Total extra space is O(V + E), and the adjacency list dominates. If the graph already arrives as an adjacency list, the extra working space is only O(V).
The O(V) bound on the queue depends on marking at push time. A star graph shows the worst case: the hub's V − 1 neighbors all sit in the queue at once.
How the Bound Breaks
The proof depends on three assumptions: O(1) queue operations, O(1) visited checks, and neighbor lookup that costs only the vertex's degree. If you break any one of them, the bound is gone.
Using `list.pop(0)` as a queue
list.pop(0) shifts every remaining element one position left, so it costs O(length of the list). In a long BFS the queue can hold O(V) items, which makes total dequeue cost O(V²). Use collections.deque and its popleft().
Using a list for the visited set
Writing if v not in visited_list: scans the list linearly. That check runs once per edge scan, which gives O(E · V). Use a boolean list indexed by vertex, as in the tutorial's code, or a set when vertices are not integers 0 to n − 1. Set lookups are O(1) on average.
Choosing a different graph representation
| Representation | Finding neighbors of u | Total traversal cost |
|---|---|---|
| Adjacency list | O(deg(u)) | O(V + E) |
| Adjacency matrix | O(V) per vertex | O(V²) |
| Raw edge list, rescanned per vertex | O(E) per vertex | O(V · E) |
With a matrix, each dequeued vertex scans a whole row of length V, whatever its degree. For dense graphs, where E is close to V², the matrix costs about the same. For the sparse graphs common in practice, the list is far faster. Searching a raw edge list for neighbors is the slowest choice of all, and this is why the first chapter builds the adjacency list before doing anything else.
Marking on pop instead of on push
The following version is also correct, but it lets duplicates into the queue.
from collections import deque
def pushes_mark_on_pop(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
seen = [False] * n
pushes = 0
for start in range(n):
if seen[start]:
continue
queue = deque([start])
pushes += 1
while queue:
u = queue.popleft()
if seen[u]:
continue
seen[u] = True
for v in adj[u]:
if not seen[v]:
queue.append(v)
pushes += 1
return pushes
k4 = [(i, j) for i in range(4) for j in range(i + 1, 4)]
print(pushes_mark_on_pop(4, k4))
# 7 (marking on push would give 4)The running time is still O(V + E), because every extra push matches an edge scan. The queue, however, can now grow to O(E) instead of O(V). On a dense graph that is the difference between V and V² memory. The pop-time check if seen[u]: continue is what keeps the version correct. If you drop that check, vertices get processed more than once.
Recursion depth
A recursive DFS has the same O(V + E) time, but the call stack can reach depth V on a path-shaped component. CPython's default recursion limit is 1000, so a path of a few thousand vertices raises RecursionError. The explicit stack in the iterative version stores the same information on the heap, with no such limit.
Edge Cases That Fit the Bound
- Self-loops: an edge (u, u) adds u to its own list twice in the undirected builder. That adds 2 to the degree sum, which still matches 2E.
- Parallel edges: each copy is stored and scanned. E counts copies, so the bound holds, but heavily duplicated edge lists inflate E. Deduplicate them first if that matters.
- Empty graph (n = 0): no loop iterations run, and the cost is O(1).
Exercise
A graph has 10,000 vertices and 0 edges. How many enqueues and how many neighbor scans does bfs_work perform, and which term of O(V + E) accounts for the running time?
Show answer
It performs 10,000 enqueues (one per vertex, each starting its own component) and 0 neighbor scans. The V term accounts for all the work: the outer loop and the queue operations. This is why the bound cannot be simplified to O(E) for component labeling.
Exercise
A colleague replaces deque with a plain list and uses queue.pop(0). On a connected path graph with V vertices, what is the new worst-case time, and why does the output stay correct?
Show answer
Each pop(0) costs time proportional to the current queue length. Total time becomes O(V + E) plus the cost of shifting elements, which is O(V²) in the worst case, for example on a star graph where the queue holds about V items. On a path the queue stays short, so the slowdown shows up on wide graphs. The output stays correct because pop(0) still removes elements in FIFO order. Only the cost per operation changes.
Exercise
You run BFS on a directed graph using only out-neighbor lists. What does the sum of adjacency list lengths equal, and does the O(V + E) bound change?
Show answer
Each directed edge is stored once, in its source's list, so the sum of out-degrees is E rather than 2E. The bound stays O(V + E). Only the constant factor on the edge term changes.