Sub topic 8
Why BFS Runs in O(V + E) Time
This chapter assumes you have already seen the BFS loop with a deque and a visited set, that you know Big-O notation, and that you can read Python dictionaries of adjacency lists. The aim is to show exactly where the work in BFS goes, so the O(V + E) bound becomes something you can check line by line. Along the way you will see the common coding mistakes that quietly break that bound.
Throughout, V is the number of vertices and E is the number of edges.
The accounting argument
Big-O analysis of BFS gets simpler if you stop thinking about the loop as a whole and charge each piece of work to something specific: a vertex or an edge.
BFS does three kinds of work:
- Queue operations. Each
appendandpoplefton adequecosts O(1). - Visited checks and updates. Each
intest andaddon a Pythonsetcosts O(1) on average. - Scanning adjacency lists. When a vertex is dequeued, BFS loops over all of its neighbors.
The key fact comes from the previous chapter. A vertex is marked visited at the moment it is enqueued, and no visited vertex is enqueued again. So each vertex enters the queue at most once and leaves it at most once. That limits queue operations to O(V).
Because each vertex is dequeued at most once, its adjacency list is scanned at most once. Scanning the list of vertex v costs O(deg(v)), where deg(v) is the number of entries in that list. The total scanning cost is the sum of all list lengths:
- In a directed graph, every edge u → v appears exactly once, in u's list. The sum of the list lengths is E.
- In an undirected graph, every edge {u, v} appears twice, once in u's list and once in v's list. The sum is 2E. This is the handshake lemma.
Each neighbor examined in a scan costs one O(1) visited check. So the edge work is O(E) either way, because the constant 2 drops out.
Adding the pieces: O(V) for vertex work plus O(E) for edge work gives O(V + E).
Seeing the counts directly
You can check the argument by counting operations. This version of BFS records how many times it dequeues a vertex and how many neighbor checks it performs.
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)
print(bfs_counted(square, 0)) # (4, 8)The directed graph has 6 vertices and 7 edges, and BFS makes exactly 6 dequeues and 7 edge checks. The undirected square has 4 vertices and 4 edges, and BFS makes 8 edge checks, one for each direction of each edge.
Why the bound says V + E and not just E
In a connected graph E ≥ V − 1, so you might expect O(E) to be enough. It is not, for two reasons.
- Sparse or empty graphs. A graph with 1,000 isolated vertices has E = 0. A full traversal that starts BFS from every unvisited vertex, as in the connected-components chapter, still touches all 1,000 vertices. Its cost is driven by V.
- Per-vertex setup. Code that allocates
dist = [-1] * nor builds{node: None for node in graph}pays O(V) before any edge is examined.
The reverse also holds. A dense graph can have E close to V², so O(V) alone would undercount badly. The sum V + E covers both extremes.
Space complexity
BFS stores three things:
- The visited set (or a
parentordistdictionary), with at most V entries. - The queue, which holds at most V vertices at once because each vertex enters it once.
- The graph itself, which takes O(V + E) as an adjacency list. Usually this is counted as input, not as extra space.
So the extra space is O(V). In practice the queue is largest when BFS is processing a wide layer. A star graph, with one center joined to V − 1 leaves, puts all V − 1 leaves in the queue at once.
Mistakes that break the bound
The O(V + E) analysis rests on specific assumptions. Each mistake below breaks one of them.
Using a list as the visited collection
visited = [start] # list, not set
if neighbor not in visited: # O(V) scan each timeMembership testing on a list scans the whole list. Each of the O(E) edge checks now costs O(V), so the total becomes O(V · E). On a graph with 10⁵ vertices and 10⁶ edges, that is the difference between about a million steps and about 10¹¹. Use a set, a dict, or a boolean list indexed by vertex number.
Using `list.pop(0)` as the queue
list.pop(0) shifts every remaining element one place left, which costs O(length of list). Over V dequeues this can add O(V²). A collections.deque gives O(1) popleft.
Marking visited on dequeue instead of enqueue
If you mark a vertex only when you pop it, the same vertex can be pushed many times before its first pop. The time stays O(V + E), because each push still corresponds to one edge check made while scanning a vertex's list once. The queue size, however, grows to O(E) instead of O(V).
from collections import deque
def pushes_mark_on_dequeue(graph, start):
visited = set()
queue = deque([start])
pushes = 1
while queue:
node = queue.popleft()
if node in visited:
continue
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
pushes += 1
return pushes
def pushes_mark_on_enqueue(graph, start):
visited = {start}
queue = deque([start])
pushes = 1
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
pushes += 1
return pushes
n = 5
complete = {u: [v for v in range(n) if v != u] for u in range(n)}
print(pushes_mark_on_dequeue(complete, 0)) # 11
print(pushes_mark_on_enqueue(complete, 0)) # 5On the complete graph with n vertices, marking on dequeue makes 1 + n(n − 1)/2 pushes, against n pushes for marking on enqueue. Dropping the if node in visited: continue guard is worse still. Vertices then get expanded repeatedly, and the running time is no longer O(V + E).
Using an adjacency matrix
With a V × V matrix, finding the neighbors of a vertex means scanning its entire row, whatever its degree. V dequeues times V columns gives O(V²). That is fine for dense graphs, where E is close to V² anyway. For sparse graphs it is much slower than an adjacency list.
Summary of costs by implementation
| Implementation choice | Time | Extra space |
|---|---|---|
| Adjacency list, `deque`, `set`, mark on enqueue | O(V + E) | O(V) |
| Same, but mark on dequeue (with skip check) | O(V + E) | O(E) |
| Visited stored in a Python list | O(V · E) | O(V) |
| Queue as a list with `pop(0)` | O(V² + E) | O(V) |
| Adjacency matrix | O(V²) | O(V) extra, O(V²) for the graph |
Implicit graphs and early exit
The same accounting works when the graph is never built explicitly. On an R × C grid with four-way moves, V = RC and each cell has at most 4 neighbors, so E ≤ 4RC and BFS runs in O(RC). The grid chapter uses exactly this bound.
Stopping early when you reach a goal vertex can save a lot of work in practice. It does not improve the worst case, because the goal might be the last vertex discovered or might be unreachable.
When the graph is too large to enumerate, as in puzzle state spaces, V and E stop being useful measures. Analysts then describe cost by branching factor b and goal depth d, giving O(b^d). The bidirectional BFS chapter builds on that view.
Exercise
An undirected graph has 50 vertices and 120 edges, and all of them are reachable from the start. How many times does a correct BFS (adjacency list, mark on enqueue) execute the body of the inner neighbor loop?
Show answer
240. Each undirected edge appears in two adjacency lists, and each list is scanned exactly once, so the inner loop runs 2E = 2 × 120 = 240 times. There are also exactly 50 dequeues.
Exercise
A teammate's BFS uses an adjacency list and a deque, but stores visited vertices in a Python list. On a graph with V = 20,000 and E = 200,000, roughly how many elementary steps could the visited checks take in the worst case, and what is the fix?
Show answer
Each of about E (or 2E) membership checks may scan up to V list entries, so the worst case is on the order of V · E = 4 × 10^9 steps. Replacing the list with a set (or a boolean list indexed by vertex) makes each check O(1) and restores O(V + E), about 2.2 × 10^5 units of work.
Exercise
Explain why BFS with an adjacency matrix costs O(V^2) even on a graph with only V − 1 edges.
Show answer
Each dequeued vertex has its full matrix row of V entries scanned to find its neighbors, no matter how few there are. With V vertices dequeued, that is V × V = V^2 checks. The edge count never enters the cost.