Union-find: who belongs together
Pairs keep arriving, “these two are connected”, and you need to answer “are these two in the same group?” at any moment. Union-find answers both in nearly constant time with one array of parent pointers and two small tricks, drawn here pointer by pointer.
01 Same group or not?
Picture friend links arriving one at a time: 0–1, 2–3, 0–2. Is 3 connected to 1 yet? A graph search answers that, but it costs O(n + e) per question, and you may ask after every link.
Another idea is to give every element a group label and relabel one whole group on each merge. Questions become O(1), but a merge can touch n elements. Union-find avoids both costs by never storing the label at all: each group is a tree, and the root is the label.
O(α(n)) per operation, which is at most 4 for any input you will ever store.02 One array of parent pointers
Union-find keeps a single array, parent. If parent[i] = i, then i is a root and names its group. Otherwise parent[i] points one step closer to the root. Two operations work on it:
find(x)follows parent pointers fromxuntil it reaches a root, and returns that root.union(a, b)finds both roots. If they differ, it points one root at the other, which merges the two whole trees with one write.
The trace below runs eight unions on eight elements. Watch the parent array: each successful union changes exactly one cell. The tag on each root is its group size, kept in a second array, size.
- root that stays
- root moved under it
- pointer just set
- elements compared
- already together
Eight people, 0 to 7, each in a group of their own. Every element is its own root: parent[i] = i, so no arrows yet.
03 Union by size keeps trees short
Which root goes under which matters. A naive union always hangs the first root under the second, and unlucky input builds a chain:
- find(0) starts here
- the root, 5 hops away
Each union hangs the whole existing tree under a single new element, so the tree only gets deeper. After n such unions, find(0) walks n hops: O(n), the same trap as a sorted insert into a plain binary search tree.
Union by size always puts the smaller tree under the root of the bigger one. An element only gets one hop deeper when its tree is merged into one at least as big, so its group at least doubles each time. A group can double at most log₂ n times, so no element is ever more than log₂ n hops from its root. In the trace, eight elements ended at most three hops deep, and log₂ 8 = 3.
Union by rank is the common alternative: it stores an upper bound on each tree’s height instead of its size and attaches the shorter under the taller. It gives the same O(log n) bound. Size is handy when the problem also asks how big a group is.
04 Path compression flattens as it goes
The second trick makes find repair the tree. Once it knows the root, it walks the same path again and points every node on it straight at the root. The walk costs nothing extra in big-O terms, since it retraces a path already paid for, and every later find from those nodes takes one hop.
- node visited now
- on the path
- the root
- re-pointed at the root
Call find(7) on the forest from the last trace. The answer is the root of 7’s tree.
With both tricks, a sequence of m operations on n elements takes O(m · α(n)) time, where α is the inverse Ackermann function. It grows so slowly that α(n) ≤ 4 for any n that could fit in a computer. That bound is amortised: a single find can still walk a few hops, but it leaves the tree flatter, so the average stays tiny.
05 The whole structure in code
This is the version from the traces, with an iterative find so a deep tree cannot hit Python’s recursion limit. It replays the same eight unions and the same find(7).
union returning False is often the whole answer. In Redundant Connection the first edge whose ends already share a root is the one that closes a cycle. Counting the True results tells you how many groups are left: start from n and subtract one for each.
06 Where union-find fits
- Connected components while edges arrive: count provinces, islands added one cell at a time, or friends circles, without re-running a search.
- Cycle detection in an undirected graph: an edge whose ends already share a root closes a cycle.
- Kruskal’s minimum spanning tree: take edges from cheapest up, keep the ones whose
unionsucceeds. - Merging records by shared keys: in Accounts Merge, give each email an index, union the emails within an account, then group emails by their root.
It cannot split a group. If edges are deleted as well as added, union-find alone does not fit: rebuild it, process the changes offline in reverse, or use a different structure.
07 When it bites
parent[b] = aLinking elements instead of rootsSetting the parent of b itself, not of find(b), cuts b out of its old tree and leaves the rest of that group behind. Always link root to root.if parent[a] == parent[b]:Comparing parents, not rootsTwo elements of one group can have different parents. Only find(a) == find(b) tells you they belong together.size[b] += size[a]Updating size at the wrong nodeSizes are only correct at roots. Add the smaller root’s size to the root that stays, after the swap, or union by size quietly stops working.return find(parent[x])Recursive find on a deep treeWithout union by size a tree can be n deep, and a recursive find in Python fails past about 1,000 levels with RecursionError. Use union by size, or the two-loop iterative find.08 Check yourself
09 Practise this
n and subtracting one for each successful union.Solve it →Coding problemRedundant ConnectionThe first union that returns False is the edge that closes the cycle.Solve it →