Essential Data Structures home
Union-Find
A structure that keeps track of which items belong to the same group, and merges groups in almost no time at all. It is also called a disjoint-set union, and it answers one question: are these two in the same group?
What it is
Union-find keeps a collection of groups, called disjoint sets, where no item belongs to more than one group. Each item starts in a group of its own. Three operations do all the work: make-set creates a new one-item group, find returns the name of the group an item belongs to, and union merges two groups into one. A fourth question, are two items in the same group, is just two finds and a comparison.
Each group is stored as a tree. The root of the tree is the group's representative, its name, and every other node points to its parent. Find follows parent pointers up to the root. Union finds the two roots and attaches one tree under the other root, so the two groups become one tree.
Two tricks keep the trees almost flat. Path compression rewires every node on the path of a find to point straight at the root, so the next find on the same nodes is a single step. Union by rank, or by size, always hangs the smaller tree under the larger root, so a tree can only grow by doubling its size, and its height stays logarithmic.
How it works
With both tricks in place, find and union run in time governed by the inverse Ackermann function, written α(n). This function grows so slowly that α(n) is 5 or less for any number of items that could ever be stored, so for practical purposes both operations take constant time. The precise statement is an amortized bound: over a long sequence of operations, the average cost is O(α(n)) per operation.
Without either trick, the structure degrades. If unions always hang the new tree under the old root in the same direction, the tree can become a chain n items deep, and a find then walks the whole chain, which is O(n). Union by rank alone keeps the height logarithmic, so a single find costs O(log n). Path compression alone keeps the average cost low but also allows a single find to cost O(log n). It is the two together that give the near-constant bound.
The classic use is Kruskal's algorithm for a minimum spanning tree. The edges of a graph are considered in order of weight, and an edge is kept only when its two endpoints sit in different groups, which is exactly the connected test. Adding the edge then merges the two groups. Union-find is what makes Kruskal's algorithm fast.
Complexity
| Operation | Average | Worst case |
|---|---|---|
| Make-set | O(1) | O(1) |
| Find | O(α(n)) amortized | O(log n) |
| Union | O(α(n)) amortized | O(log n) |
| Connected (same set?) | O(α(n)) amortized | O(log n) |
n is the number of items, and α(n) is the inverse Ackermann function, 5 or less for any practical n. The worst case column assumes union by rank (or by size); without it, find can degrade to O(n). The structure uses O(n) space, one parent pointer per item.
When to use it, and when not to
Use union-find when the problem is about grouping: connected components in a graph, Kruskal's minimum spanning tree, labeling connected regions in an image, percolation, and grouping accounts or records that share an identifier. If the work is a stream of merge and same-group questions, nothing beats it.
Do not use it when groups need to split apart. Union-find merges efficiently but has no cheap way to undo a merge or remove an item from a group. Do not use it when you need to list the members of a group, since the tree stores parents, not children, and listing a group means scanning every item. And do not use it for lookup by key or for ordered data, which are a hash table's job and a tree's job.
Where you meet it
Inside Kruskal's algorithm, which builds minimum spanning trees for networks and road layouts. In image processing, where connected pixels are labeled as one region. In maze generation, where walls are removed between cells in different groups until the whole maze is one group. In compilers and type checkers, where union-find groups together types that must be equal. And in any system that asks, over and over, whether two things are already connected.
In Python
class UnionFind:
def __init__(self, items):
self.parent = {item: item for item in items}
self.size = {item: 1 for item in items}
def find(self, item):
# Path compression: point each node straight at the root
root = item
while self.parent[root] != root:
root = self.parent[root]
while self.parent[item] != item:
self.parent[item], item = root, self.parent[item]
return root
def union(self, a, b):
# Union by size: the smaller tree hangs under the larger root
root_a, root_b = self.find(a), self.find(b)
if root_a == root_b:
return False
if self.size[root_a] < self.size[root_b]:
root_a, root_b = root_b, root_a
self.parent[root_b] = root_a
self.size[root_a] += self.size[root_b]
return True
def connected(self, a, b):
return self.find(a) == self.find(b)
uf = UnionFind(["A", "B", "C", "D", "E"])
uf.union("A", "B")
uf.union("C", "D")
print(uf.connected("A", "B")) # True, same group
print(uf.connected("A", "C")) # False, different groups
uf.union("B", "C")
print(uf.connected("A", "D")) # True, the two groups are now one
In short: union-find answers one question, are these two in the same group, and it answers it in practically constant time by keeping its trees almost flat.
Sources
- Disjoint-set data structure, Wikipedia
- Python tutorial, Data Structures
- Cormen, Leiserson, Rivest, and Stein, Introduction to Algorithms, chapter 21