Sub topic 2
Why Traversal Runs in O(V + E)
This chapter assumes you can read Python classes, know Big-O notation, and have seen BFS and DFS labeling build an adjacency list and visit each component.
Why Traversal Runs in O(V + E)
Each vertex gets marked once, when it is first discovered. After that it never enters the queue or stack again. Each vertex's adjacency list is scanned once, when that vertex is removed. In an undirected graph every edge appears in two lists, so the scanning costs 2E steps in total. The outer loop over start vertices adds V steps. The total is O(V + E) time.
Space is O(V + E) for the adjacency list, plus O(V) for the labels and the queue or stack.
Counting Islands: Components in a 2D Grid
A grid is an implicit graph. Each '1' cell is a vertex, and its edges go to the up, down, left, and right neighbors. You compute neighbors as you go, so you never build an adjacency list. Flood fill is DFS on this implicit graph.
def count_islands(grid):
rows, cols = len(grid), len(grid[0])
seen = [[False] * cols for _ in range(rows)]
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != '1' or seen[r][c]:
continue
count += 1
seen[r][c] = True
stack = [(r, c)]
while stack:
y, x = stack.pop()
for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
ny, nx = y + dy, x + dx
if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == '1' and not seen[ny][nx]:
seen[ny][nx] = True
stack.append((ny, nx))
return count
print(count_islands(["11000", "11000", "00100", "00011"])) # 3Each cell has at most four edges, so the cost is O(rows × cols).
Union-Find: Merging Sets Instead of Traversing
Union-find, also called a disjoint set, does not traverse the graph. Every vertex starts in its own set. For each edge you call union(u, v), which merges the sets holding u and v. find(x) returns the root of the set that contains x. Two vertices are in the same component exactly when their roots match.
Path Compression and Union by Size
Without any optimization, the trees can grow into long chains, and each find then costs O(V). Two fixes keep the trees shallow:
- Union by size hangs the smaller tree under the root of the larger one.
- Path compression points every node on a
findpath directly at the root.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.components = n
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root:
self.parent[x], x = root, self.parent[x]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.components -= 1
return True
ds = DisjointSet(6)
for u, v in [(0, 1), (1, 2), (3, 4)]:
ds.union(u, v)
print(ds.components) # 3With both fixes, each operation costs O(α(V)) amortized. α is the inverse Ackermann function, which stays below 5 for any graph you could store. Space is O(V), and you need no adjacency list at all.
| Method | Time | Extra space |
|---|---|---|
| BFS / DFS | O(V + E) | O(V + E) |
| Union-find | O(V + E·α(V)) | O(V) |
Exercise
An iterative DFS marks vertices as seen only when they are popped. What is the worst-case stack size, and why?
Show answer
O(E). A vertex can be pushed once for each edge that reaches it before it is popped, so the stack can hold an entry for every edge endpoint. Marking a vertex when it is pushed caps the stack at O(V).
Exercise
Why does union-find need only O(V) space while BFS needs O(V + E)?
Show answer
Union-find handles each edge once as it arrives and then discards it. It stores only the parent and size arrays. BFS must keep every edge in the adjacency list.