Sub topic 8
Why BFS Runs in O(V + E) Time
This chapter assumes you know Big-O notation, can read the queue-based BFS from earlier chapters, and understand why BFS marks a vertex as visited when it is enqueued. V is the number of vertices and E is the number of edges.
The accounting argument
BFS does two kinds of work: queue operations and neighbor checks. You can bound each one separately and then add the two bounds.
- Each vertex is enqueued at most once. A vertex is added to the visited set at the moment it is enqueued, and the
if neighbor not in visitedtest stops it from being enqueued again. That gives at most V enqueues and V dequeues, each O(1) withdeque. - Each adjacency list is scanned once. BFS scans a vertex's neighbor list only when it dequeues that vertex. Since each vertex is dequeued once, each list is scanned once. Over the whole run, the number of neighbor checks equals the total length of all adjacency lists. That total is E in a directed graph and 2E in an undirected graph, because each undirected edge appears in two lists.
Adding the two parts gives O(V) + O(E) = O(V + E).
Counting it directly
Add counters to BFS to see the bound in practice:
from collections import deque
def bfs_counted(graph, start):
visited = {start}
queue = deque([start])
dequeues = 0
edge_checks = 0
while queue:
node = queue.popleft()
dequeues += 1
for neighbor in graph[node]:
edge_checks += 1
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return dequeues, edge_checks
directed = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D', 'E'],
'D': ['F'], 'E': ['F'], 'F': []}
square = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}
print(bfs_counted(directed, 'A')) # (6, 7): V = 6, E = 7
print(bfs_counted(square, 0)) # (4, 8): V = 4, 2E = 8If the graph is disconnected, BFS from one source touches only the reachable part, so the cost is O(Vr + Er) for the reachable vertices and edges. When you loop over every vertex to find connected components, each vertex and edge is still processed once overall, so the total stays O(V + E).
Space
The visited set, the queue, and any parent or distance map each hold at most V entries, so extra space is O(V). The adjacency list itself takes O(V + E).
How the representation changes the bound
| Representation | Cost to list a vertex's neighbors | Total BFS time |
|---|---|---|
| Adjacency list | O(degree) | O(V + E) |
| Adjacency matrix | O(V), since the whole row is scanned | O(V²) |
| Implicit grid (R × C) | O(1), with 4 fixed neighbors | O(R · C) |
On sparse graphs, an adjacency matrix gives up the O(V + E) bound.
Common errors that break the bound
Exercise
An undirected graph stored as adjacency lists has 1,000 vertices and 5,000 edges and is connected. Exactly how many neighbor checks does bfs_counted perform, and how many dequeues?
Show answer
It performs 1,000 dequeues, one per vertex. It performs 10,000 neighbor checks, because each undirected edge appears in two adjacency lists, so the total list length is 2E = 10,000.
Exercise
A BFS uses a Python list as the queue with pop(0) and a list for visited. What is its worst-case running time on a connected graph?
Show answer
Each of the V dequeues costs O(V), which gives O(V²). Each of the O(E) neighbor checks does an O(V) membership test, which gives O(V · E). The total is O(V² + V · E), compared with O(V + E) for the correct version.
Exercise
For a complete undirected graph on n vertices, is BFS with an adjacency list asymptotically faster than BFS with an adjacency matrix?
Show answer
No. E = n(n − 1)/2, so O(V + E) = O(n²), the same as the matrix bound. Adjacency lists only pay off when the graph is sparse.