Sub topic 7
Union-Find: Merging Sets Instead of Traversing
This chapter assumes you can read Python classes and you know the component definition from earlier chapters. You should also be comfortable with Big-O notation. BFS and DFS find components by walking the whole graph at once. Union-find takes a different approach. It keeps a collection of disjoint sets and merges two sets whenever an edge joins them. It never builds an adjacency list, and it never visits neighbors.
The Working Model
Each vertex starts in its own set. Every set is stored as a tree of parent pointers, and the root of the tree is the set's representative. The structure supports two operations:
find(x)follows parent pointers fromxuntil it reaches a vertex that is its own parent. That vertex is the root. Two vertices are in the same component exactly whenfindreturns the same root for both.union(a, b)finds the roots ofaandb. If the roots differ, it makes one root the parent of the other, which merges the two sets.
A component counter starts at n, the number of vertices. It drops by one every time union merges two different sets.
class SimpleDisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.components = n
def find(self, x):
while self.parent[x] != x:
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
self.parent[rb] = ra
self.components -= 1
return True
ds = SimpleDisjointSet(6)
for u, v in [(0, 1), (1, 2), (3, 4)]:
ds.union(u, v)
print(ds.components) # 3
print(ds.parent) # [0, 0, 0, 3, 3, 5]
print(ds.find(2) == ds.find(0)) # True
print(ds.find(5) == ds.find(3)) # False
print([ds.find(x) for x in range(6)]) # [0, 0, 0, 3, 3, 5]The last line gives every vertex a label, just as BFS labeling did. Here the labels are root vertices instead of the numbers 0, 1, 2, …. If you need consecutive numbers, map each distinct root to a new index.
When union(1, 2) runs, vertex 2 attaches to 0, not to 1. That is because union always links the roots, never the vertices it was given.
Union-Find Compared with Traversal
| Aspect | BFS / DFS | Union-find |
|---|---|---|
| Input needed | Full adjacency list | Edges one at a time, in any order |
| Extra memory | Adjacency list + visited array + queue/stack | One parent array (plus a size array once optimized) |
| New edge added later | Re-run or patch the traversal | One `union` call |
| Can it delete edges? | Re-run | No |
Union-find is a good fit when edges arrive as a stream, or when you only need to ask "are these two connected?" It cannot undo a merge. If you remove edges, you have to rebuild.
Common Errors
- Linking vertices instead of roots. Writing
parent[b] = athrows away whateverbwas already attached to and splits its set. Always callfindon both sides first. - Skipping the same-root check. Without
if ra == rb, an edge inside a component still decrementscomponents, and the count becomes wrong as soon as the graph has a cycle. - Comparing parents instead of roots.
parent[x] == parent[y]fails for vertices at different depths. Comparefind(x) == find(y).
Exercise
Using SimpleDisjointSet(5), run union(2, 3), union(3, 4), union(0, 4) in that order. What are the final parent array and component count?
Show answer
union(2,3) sets parent[3]=2. union(3,4) finds roots 2 and 4 and sets parent[4]=2. union(0,4) finds roots 0 and 2 and sets parent[2]=0. The parent array is [0, 1, 0, 2, 2] and components is 2: the sets {0, 2, 3, 4} and {1}.
Exercise
The graph has edges (0,1), (1,2), (2,0). Starting from 3 components, what count would union produce if the ra == rb check were removed, and why?
Show answer
It would produce 0. The first two edges merge everything and bring the count down to 1. The third edge joins two vertices that already share a root, but without the check it still decrements the count. The correct answer is 1.