Groups as trees
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.
Each element stores one number: its parent. At the start parent[i] = i, so every element points at itself. An element that is its own parent is a root, and the root names its group. Six roots: six groups.
Union and find
union(0, 1) first finds each root: 0 and 1, both alone. They differ, so root 1 becomes a child of root 0: parent[1] = 0. One write merges two groups, and size[0] becomes 2.
union(2, 3) and union(4, 5) work the same way: parent[3] = 2 and parent[5] = 4. Now there are three groups of two. Each group is a small tree, and every arrow points from a child up to its parent.
union(1, 3): find(1) climbs to root 0 and find(3) climbs to root 2. Both trees have size 2, a tie, so root 2 goes under root 0: parent[2] = 0. Element 3 comes along; its parent is still 2.
find(x) follows parent arrows until it reaches an element that points at itself. find(3) goes 3 → 2 → 0: two hops, and 0 is the root. The deeper an element sits, the longer its find takes.
Keeping trees flat
On its way back, find(3) points 3 straight at the root: parent[3] = 0. The answer is the same, but the next find(3) takes one hop. This is path compression: every find flattens the path it walked.
union(5, 3): find(5) gives root 4, size 2; find(3) gives root 0, size 4. The smaller tree hangs under the bigger root: parent[4] = 0 and size[0] = 6. Only a root’s size is ever read. No element ends up deeper than log₂ n.
Same group? Compare roots. find(5) climbs 5 → 4 → 0, then compresses: parent[5] = 0. find(1) reaches 0 in one hop. Both roots are 0, so the answer is yes. Now every element points directly at 0.
With both tricks, any m operations on n elements take O(m α(n)) time. α, the inverse Ackermann function, is at most 4 for any n you could ever store. Kruskal’s spanning tree algorithm, later in this course, relies on it.
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.