Union-find (disjoint-set) answers “are these two things connected?” over a stream of merges, using a parent array where each element points toward a representative root. Two optimizations make it astonishing: union by rank attaches the smaller tree under the larger, and path compression re-points every node to the root as you traverse it — so the structure flattens itself with use. Together they give an amortized cost of the inverse Ackermann function, effectively constant — a query makes future queries faster. It is the engine of Kruskal’s MST, connected components, and cycle detection. Connect {0-1, 2-3, 1-3} and 0..3 collapse into one set; 4 stands alone — 2 components.
The demo unions {0-1, 2-3, 1-3} — 0 and 3 become connected, and five singletons collapse to 2 components: live demo
“Connectivity queries get slower as you add merges.” — path compression flattens the structure with use, so queries stay near-constant. cited
A structure that gets faster the more you query it, folding its own paths flat — connectivity at near-constant cost. self-flattening
On the canonical compiler, unioning {0-1, 2-3, 1-3} connects 0 and 3 and leaves 2 components (the merged {0,1,2,3} and the singleton 4):