Sub topic 7
Union-Find: Merging Sets Instead of Traversing
This chapter assumes you already know how to build an adjacency list, how BFS and iterative DFS label components, and why those traversals run in O(V + E). It also assumes you can read a small Python class.
Union-find, also called a disjoint set union (DSU), finds connected components without traversing anything. You never build an adjacency list and you never visit neighbors. You read the edges one at a time, and each edge says "these two vertices belong to the same group." The data structure merges the two groups if they are different. After the last edge, the groups that remain are the connected components.
The Core Idea: Groups That Only Merge
Think about what an edge (u, v) means for components. If u and v are already in the same component, the edge changes nothing. If they are in different components, the edge joins those two components into one. Nothing else can happen. Components never split, and an edge can never affect a third component.
So you need only two operations:
find(x): return a representative vertex for the group that contains x. Two vertices are in the same group exactly whenfindreturns the same representative for both.union(a, b): merge the group containing a with the group containing b.
Start with every vertex in its own group of size one, which gives n components. Call union(u, v) for every edge. Each union that actually merges two groups reduces the component count by one.
Representing Groups as a Forest
Union-find stores each group as a tree, using a single array called parent. Every vertex points to a parent vertex. A vertex that points to itself is a root, and the root is the representative of its group. To find the representative of x, follow parent pointers until you reach a vertex whose parent is itself.
To merge two groups, find both roots and make one root point to the other. That one pointer change moves the whole smaller tree under the other root. No other vertex has to change.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n)) # every vertex starts as its own root
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 # already in the same component
self.parent[rb] = ra # link root to root
self.components -= 1
return True
ds = DisjointSet(6)
for u, v in [(0, 1), (1, 2), (3, 4)]:
ds.union(u, v)
print(ds.parent) # [0, 0, 0, 3, 3, 5]
print(ds.components) # 3
print(ds.find(2) == ds.find(0)) # True
print(ds.find(5) == ds.find(3)) # FalseThis is the same six-vertex graph the BFS and DFS chapters used. The count of 3 matches.
Tracing the Unions
Walk through the three edges and watch the parent array change.
| Step | Edge | find(a) | find(b) | Change | parent | components |
|---|---|---|---|---|---|---|
| start | none | none | none | none | [0, 1, 2, 3, 4, 5] | 6 |
| 1 | (0, 1) | 0 | 1 | parent[1] = 0 | [0, 0, 2, 3, 4, 5] | 5 |
| 2 | (1, 2) | 0 | 2 | parent[2] = 0 | [0, 0, 0, 3, 4, 5] | 4 |
| 3 | (3, 4) | 3 | 4 | parent[4] = 3 | [0, 0, 0, 3, 3, 5] | 3 |
In step 2, find(1) does not return 1. Vertex 1 already points to 0, so its root is 0. The union therefore links vertex 2 under root 0, and all three vertices end up in one tree.
The forest's arrows point from child to parent, so they point upward toward the root. These trees are bookkeeping, not the graph. Vertices 0 and 2 are not adjacent in the input graph, but 2 points directly to 0 in the forest. Union-find records which vertices are in the same component and throws away the actual paths between them.
Turning Roots into Component Labels
BFS gave you a label array with components numbered 0, 1, 2, and so on. Union-find gives you roots, and root ids such as 0, 3, and 5 are arbitrary. To get the same kind of output, number each root the first time you meet it:
def components_union_find(n, edges):
ds = DisjointSet(n)
for u, v in edges:
ds.union(u, v)
root_to_label = {}
label = [0] * n
groups = []
for v in range(n):
r = ds.find(v)
if r not in root_to_label:
root_to_label[r] = len(groups)
groups.append([])
label[v] = root_to_label[r]
groups[label[v]].append(v)
return ds.components, label, groups
print(components_union_find(6, [(0, 1), (1, 2), (3, 4)]))
# (3, [0, 0, 0, 1, 1, 2], [[0, 1, 2], [3, 4], [5]])This loop needs the DisjointSet class from the previous block. Its output matches both the BFS labels and the DFS component lists exactly.
A Free Bonus: Detecting Redundant Edges
union returns False when both endpoints already share a root. That means the graph already had a path between them, so the new edge closes a cycle. This is how Kruskal's minimum spanning tree algorithm rejects edges, and it is how you find the extra edge in an otherwise tree-shaped graph.
ds = DisjointSet(4)
for u, v in [(0, 1), (1, 2), (2, 0), (2, 3)]:
if not ds.union(u, v):
print("redundant edge:", (u, v))
# redundant edge: (2, 0)
print(ds.components) # 1A traversal can detect cycles too, but it needs extra parent tracking. Union-find gives you cycle detection for free.
Common Mistakes
Most union-find bugs come from a handful of patterns.
- Linking vertices instead of roots. Writing
parent[b] = ainstead ofparent[find(b)] = find(a)breaks the structure. If b is not a root, the assignment detaches b's subtree from its old group. That group's other members stay behind, so the group splits silently. - Decrementing the count on every edge. Only a successful merge reduces the component count. If you decrement for an edge whose endpoints already share a root, the count comes out too low whenever the graph has a cycle.
- Comparing parents instead of roots.
parent[a] == parent[b]can be false for two vertices in the same tree when they sit at different depths. Comparefind(a) == find(b). - Forgetting isolated vertices. Vertices that appear in no edge are still components. Size the structure with n, the number of vertices, not with the largest id that appears in the edge list. Vertex 5 above is counted only because
DisjointSet(6)created it.
The Cost of the Simple Version
Space is O(V): one integer per vertex. Union-find never stores the edges. That matters when edges arrive from a file or a network stream that you cannot or do not want to keep in memory. BFS and DFS need the whole adjacency list, which takes O(V + E) space, before they can start.
Time depends on tree height, because find walks from a vertex to its root. The version above has no rule for which root goes on top, and that can produce a long chain:
def depth(ds, x):
d = 0
while ds.parent[x] != x:
x = ds.parent[x]
d += 1
return d
n = 1000
ds = DisjointSet(n)
for i in range(1, n):
ds.union(i, i - 1) # root of i's group goes on top every time
print(depth(ds, 0)) # 999Each union makes the old chain hang under a new root, so vertex 0 ends up 999 steps from the top. In the worst case a single find costs O(V), and processing E edges costs O(V · E). That is much worse than the O(V + E) of a traversal.
The next chapter fixes this with two small changes. Union by size always hangs the smaller tree under the larger one. Path compression makes every vertex on a find path point straight to the root. Together they bring the cost per operation down to nearly constant.
Traversal or Union-Find?
| Situation | BFS / DFS | Union-find |
|---|---|---|
| All edges known up front, graph already in memory | Natural fit, O(V + E) | Works, no real advantage |
| Edges arrive one at a time, queries in between | Must re-traverse after changes | Natural fit |
| Memory limited, edges streamed | Needs the full adjacency list | O(V) memory only |
| Need actual paths or distances | BFS gives them | Paths are lost |
| Detect the edge that closes a cycle | Needs extra bookkeeping | `union` returns `False` |
| Directed graphs, strong connectivity | Basis of Kosaraju and Tarjan | Not applicable |
Union-find answers only one question: are these two vertices in the same group? In exchange for that narrow focus, it handles edges in any order and never looks at the graph as a whole. It also only merges. If an edge is deleted, union-find cannot split a group back apart.
Exercise
Starting from DisjointSet(5), apply union(3, 4), union(1, 3), union(0, 2), and union(4, 1), using the simple class from this chapter. What is the parent array afterward, what is the component count, and what does the last call return?
Show answer
union(3, 4) sets parent[4] = 3. union(1, 3) finds roots 1 and 3 and sets parent[3] = 1. union(0, 2) sets parent[2] = 0. union(4, 1) finds root 1 for both vertices, because 4 points to 3 and 3 points to 1, so it returns False and changes nothing. The final parent array is [0, 1, 0, 1, 3] and there are 2 components: {0, 2} and {1, 3, 4}.
Exercise
A teammate writes union as "if self.find(a) != self.find(b): self.parent[b] = a; self.components -= 1". Give a short sequence of unions on 4 vertices where this produces a wrong answer, and explain why.
Show answer
Use union(0, 1), then union(2, 1). The first call sets parent[1] = 0. The second call sees roots 2 and 0, which differ, so it sets parent[1] = 2 and decrements the count to 2. Vertex 1 has now left its old tree, so find(0) returns 0 while find(1) and find(2) return 2. All three vertices should be in one component, with a count of 2 including vertex 3. Instead the count of 2 refers to {0}, {1, 2}, and an uncounted {3}, and a query asking whether 0 and 1 are connected wrongly returns False. The fix is to link the roots: parent[find(b)] = find(a).
Exercise
You receive 50 million edges over a network connection for a graph with 2 million vertices. You need the number of connected components at the end and cannot store the edges. Which method fits, and what is its memory cost?
Show answer
Union-find. It processes each edge as it arrives and discards it, so it needs only the parent array and the counter: O(V) memory, about 2 million integers. BFS or DFS would need to store all 50 million edges in an adjacency list first. Use the optimized version from the next chapter so the total running time stays close to linear.