SpecializedSpecialized Structures
Union-Find (Disjoint Set Union)
Tracks a partition of elements into disjoint sets with near-constant-time find and union, using path compression and union by rank.
a
0
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
rank
0
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
parent[i] shown below — i is a root when parent[i] = i · n = 8
Sets
| root | rank | members |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 2 | 0 | 2 |
| 3 | 0 | 3 |
| 4 | 0 | 4 |
| 5 | 0 | 5 |
| 6 | 0 | 6 |
| 7 | 0 | 7 |
1/638 elements, each its own set: parent[i] = i and rank 0. The parent array encodes a forest; the root of a tree names its set.
Element being processedOn the path to the rootSet representativeRelinked (compression / union)
PseudocodeLearn Union-Find (Disjoint Set Union) →
1find(x): while parent[x] != x: x = parent[x] # walk to the root2 path compression: point every node on the path directly at the root3union(a, b): ra = find(a); rb = find(b)4 if ra == rb: already same set5 attach the root with smaller rank under the other (union by rank)6 if ranks are equal: rank[new root] += 1Variables
n8
sets8
Complexity
access —
search O(α(n))
insert O(1)
delete —
Speed