UNION-FIND
Nearly O(1) connectivity queries via path compression and union by rank
Each element has a parent link, and find walks the links up to a root. Naive union(a, b) hangs root(a) under root(b). You run union(0,1), union(1,2), …, union(14,15) on 16 elements. How many parent links does find(0) follow?
Union-find keeps disjoint sets as a forest. Each element points at a parent; a root points at itself and names the set. find(x) walks up to the root. union(a, b) finds both roots and points one at the other.
Nothing in that description says which root goes under which. Choose badly and the forest becomes a linked list, so find is O(n). Two fixes exist. Union by rank hangs the shorter tree under the taller one, so height stays at most log2 n. Path compression points every node a find walks past straight at the root.
function find(x) {
while (parent[x] !== x) x = parent[x]; // walks the whole chain
return x;
}
function union(a, b) {
parent[find(a)] = find(b); // order of arguments decides the shape
}function find(x) {
if (parent[x] !== x) parent[x] = find(parent[x]); // path compression
return parent[x];
}
function union(a, b) {
let ra = find(a), rb = find(b);
if (ra === rb) return;
if (rank[ra] < rank[rb]) [ra, rb] = [rb, ra];
parent[rb] = ra; // shorter tree under taller
if (rank[ra] === rank[rb]) rank[ra]++;
} The invariant strip tracks the worst find against log2 n + 1. NAIVE breaks it and stays broken. COMPRESSION ONLY breaks it once, on the first find, then the tree is flat. RANK + COMPRESSION runs the same unions and never builds a chain at all.
Without rank or compression, the chain of unions builds one long path. Raise ELEMENTS until finding every element once costs more than 1000 parent hops.
GOAL: naive: the find-every-element pass costs > 1000 hops
Make find do full path compression (every node it walks past ends up pointing straight at the root) and make union attach the lower-rank root under the higher one. The grader runs a 1024-element chain of unions, checks tree height <= log2 n + 1, checks that every node on a find’s path now points at the root, and compares connectivity with a reference. (Path halving and path splitting have the same bound but only shorten the path, so they do not pass this check.)
Kruskal's MST, connected components in image segmentation and graph processing, type unification in compilers (Hindley-Milner), equivalence classes in alias analysis, and network partition detection. The symptom without the fixes: a job that is fast on random data and quadratic on sorted data.
“Implement union-find” or “count connected components as edges arrive.” Write both optimizations, say why each matters (rank bounds height at log n; compression amortizes to near O(1)), and name α(n). Mention that union by size works as well as union by rank.