1def find(x):2 if parent[x] != x:3 parent[x] = find(parent[x])4 return parent[x]5def union(a, b):6 ra, rb = find(a), find(b)7 if ra == rb:8 return9 if size[ra] < size[rb]:10 ra, rb = rb, ra11 parent[rb] = ra12 size[ra] += size[rb]001122334455011121314151parentsize012345
Pucks: the six elements; an arrow points from each to its parentRows: the parent and size arrays, indexed 0 to 5The small token: find climbing the arrows to a rootEach element stores its parent; a root points at itself and names its group, so every group is a tree. union links one root under the other, find climbs the arrows to the root. Union by size and path compression keep the trees flat, so a sequence of m operations costs O(m α(n)).

Groups as trees

  1. Six people, numbered 0 to 5. Friendships arrive one at a time, and we keep asking: are a and b in the same group? Groups only ever merge. Union-find answers this quickly, without searching the whole graph again.

Union and find

Keeping trees flat

What happens

;; step 1/10 · groups
no structure yet: just six separate elements

parent = [0, 1, 2, 3, 4, 5]
size   = [1, 1, 1, 1, 1, 1]

Why log₂ n: an element only gets deeper when its tree is hung under a tree at least as big, so its group at least doubles each time. A group cannot double more than log₂ n times. This lesson uses union by size, as in Sedgewick and Wayne. CLRS uses union by rank, which links by an upper bound on tree height instead of member count. Both keep every tree at most log₂ n deep, and both give the O(m α(n)) bound with path compression.