Union-find

Disjoint sets, path compression, and the problems it makes trivial.

8 min read🧮 Data Structures and Algorithms in Java

Union-find answers one question — are these two things in the same group? — and answers it in effectively constant time, for a problem that looks like it should need a graph traversal.

It is small enough to write from memory and it is the right answer surprisingly often.

The structure

Every element points at a parent. Follow parents until you reach one that points at itself: that is the group's representative. Two elements are in the same group when they have the same representative.

java
int[] parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;      // everyone is their own group
 
int find(int x) {
    while (parent[x] != x) x = parent[x];
    return x;
}
 
void union(int a, int b) {
    parent[find(a)] = find(b);                   // point one representative at the other
}

That is a complete implementation, and it has one problem: the trees can degenerate into a chain, and then find is O(n).

Path compression, measured

A deliberate worst case — a chain of a hundred thousand — then find on every element:

plaintext
###   without path compression   3069 ms
###   with path compression         1 ms

Three thousand times, and the change is one line inside the loop:

java
int find(int x) {
    while (parent[x] != x) {
        parent[x] = parent[parent[x]];    // point at grandparent on the way past
        x = parent[x];
    }
    return x;
}

Every find flattens the path it walked, so the work is done once and every later query is short. This is the same idea as memoisation in the previous lesson: pay once, and leave the answer where you will look next time.

The second optimisation is union by rank (or size): when joining two trees, hang the shorter under the taller, so the result stays shallow. With both, the amortised cost is the inverse Ackermann function — a value below 5 for any n you will ever have, which is why union-find is described as "effectively constant".

What it is for

The pattern is: things get merged into groups, and you need to ask about membership as you go.

  • Cycle detection while building. Adding an edge between two vertices already in the same group creates a cycle. This is Kruskal's minimum spanning tree, and it is the classic use.
  • Connected components. Union every edge; count distinct representatives.
  • "Are these two accounts the same person?" Merge on each piece of evidence, query at any point.
  • Grid problems — islands, percolation — where adjacent cells merge.
  • Detecting a cycle in a dependency graph as it is constructed, rather than after.

And what it is not for, which is the part that decides whether to reach for it:

  • It cannot un-merge. There is no split. If groups can come apart, this is the wrong structure and you need something that recomputes.
  • It does not give you the path, only whether one exists. "Are A and B connected" — yes. "How are they connected" — use BFS.
  • It has no order. The representative is an arbitrary member, not a smallest or a first.

Against the alternative

For "are these connected", the obvious alternative is DFS or BFS from one of them.

Union-findBFS/DFS
one query on a static graphoverkillfine, O(V+E)
many querieseffectively O(1) eachO(V+E) every time
edges arriving over timenatural — just unionrebuild and re-traverse
needs the actual pathcannotyes

So the decision is: many queries, or a graph that grows. A single connectivity question on a graph you already have is a traversal. Ten thousand questions, or edges arriving one at a time, is union-find.

Under the hood: why the inverse Ackermann function, and what it actually bounds

"Effectively constant" is not a hand-wave — it names a real, proven bound, and it is worth knowing where the bound comes from, even loosely.

With union by rank alone (no compression), a tree's height is bounded by O(log n): hanging the shorter tree under the taller one means the height only increases when two trees of equal height merge, and even then by just one — the same argument that keeps a balanced binary tree at log n height. That alone caps every find at O(log n), which is already fast.

Path compression alone (no rank) gives an amortised bound of O(log n) per operation too, by a different argument: every find that walks a long path flattens it, so the total work across m operations is bounded by O(m log n) — the cost is paid once per path, not once per query on that path, which is exactly the "pay once, leave the answer where you'll look next time" framing this lesson already uses for memoisation.

Combined, the proven bound is O(α(n)) amortised per operation, where α is the inverse Ackermann function — the inverse of a function that grows so explosively (Ackermann's function passes numbers with more digits than atoms in the observable universe at inputs as small as 4) that its inverse grows correspondingly absurdly slowly. α(n) is at most 4 for any n you could physically construct — you would need a number of elements vastly larger than the number of particles in the universe to push α(n) past 5. That is the precise sense in which "effectively constant" is not an approximation: it is a real, proven, non-constant bound that happens to never take a value above 4 in any input that could exist.

Try it yourself

Trace what one find flattens

java
int[] parent = {1, 2, 3, 4, 4};   // chain 0->1->2->3->4, 4 is its own parent
System.out.println("before: [" + parent[0] + ", " + parent[1] + ", " + parent[2] + ", " + parent[3] + ", " + parent[4] + "]");
int x = 0;
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
System.out.println("after:  [" + parent[0] + ", " + parent[1] + ", " + parent[2] + ", " + parent[3] + ", " + parent[4] + "]");

Before running it: find(0) walks the chain 0→1→2→3→4. The lesson's one-line technique points each node at its grandparent as it passes, not straight at the root. Does one call to find(0) flatten the whole chain to point directly at 4, or does it only get partway there?

Why this is path halving, not full compression, in one pass

Only partway: x jumps from 0 to 2 to 4, so the loop only ever touches indices 0 and 2 — node 1 is skipped entirely and is left pointing at the old 2, itself now compressed but not all the way to the root. This technique is properly called path halving: each visited node's distance to the root roughly halves rather than collapsing to one hop. It still gets the same amortised bound as textbook path compression (which instead does a second pass, re-walking the path once the root is known, to point every node straight at it) — path halving is simply the cheaper one-pass version, which is exactly why this lesson's find is short enough to write from memory. A second call to find(0) would finish flattening what the first one left behind.

Misconceptions

  • "Path compression changes which representative a group has." It never does — it only shortens the paths to whichever representative already exists. find always returns the same root before and after compression; compression is purely an optimisation of future lookups, not a change to group membership.
  • "Union by rank without path compression is not worth doing." It is, on its own: O(log n) per find is already far better than the unbounded chain this lesson opens with, and it needs no extra bookkeeping beyond one small rank[] array. The two optimisations are independent and each pays for itself separately; combining them is what reaches the inverse-Ackermann bound, not a requirement for either to help.

Sources

  • Robert Sedgewick and Kevin Wayne, Algorithms (4th ed.) — union-find, weighted quick-union with path compression, and the amortised analysis.
  • Thomas H. Cormen et al., Introduction to Algorithms (CLRS) — the disjoint-set forest, union by rank, path compression, and the inverse Ackermann bound.
  • Robert E. Tarjan, "Efficiency of a Good But Not Linear Set Union Algorithm" (1975) — the original proof of the inverse-Ackermann amortised bound.
Progress is saved on this device and to your account when signed in.