Each group is a small tree stored in a parent array, with the root as the group's representative. Two tricks keep the trees flat: attach the smaller tree under the larger one, and point every node you visit straight at the root. With both, each operation is close to constant time.
When to use it
- Connections arrive one at a time and you need to know whether two items are already connected.
- The question asks for the number of connected components, groups, provinces or islands after merges.
- You need to detect a cycle while adding edges to an undirected graph, as in Kruskal's minimum spanning tree.
- Items that share something (an email, a value) must be merged into accounts or groups.
The template
parent = list(range(n)) # each item starts as its own group
size = [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path compression (halving)
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False # same group: edge makes a cycle
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra # union by size: small tree under big
size[ra] += size[rb]
return TrueThe variants you will meet
Find and union
Every item starts as its own root. Find follows parent links to the root; union finds both roots and points one at the other. Two items are connected when their roots match.
Union by rank or size
Always hang the shorter (or smaller) tree under the taller (or larger) one, so trees stay O(log n) deep even before path compression.
Path compression
While finding the root, repoint each node you pass closer to it. Later finds on those nodes take one or two steps.
Counting and connectivity
Start with n components and subtract one for every union that merges two different roots. Answer connectivity questions as edges arrive, or offline by sorting the queries first.
Time and space complexity
With path compression and union by rank or size, a sequence of m operations takes O(m · α(n)), where α is the inverse Ackermann function: below 5 for any n you will ever meet, so effectively O(1) each. Space is O(n) for the parent and size arrays.