Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Union-Find & the Inverse Ackermann Function

Path compression, union by rank and Tarjan’s analysis.

Two changes of a few lines each, linking by rank and compressing paths, make union-find so fast that mm operations cost O(m α(n))O(m\,\alpha(n)), where α(n)≤4\alpha(n) \le 4 for any nn that could ever be stored. Tarjan proved the bound in 1975 and showed in 1979 that it is tight for a broad class of pointer algorithms; in 1989 Fredman and Saks proved that no data structure whatsoever can beat it.

What you’ll learn

  • Prove the rank lemmas of union by rank and the ⌊log⁡2n⌋\lfloor \log_2 n \rfloor height bound, and compare the four combinations of linking and compression.
  • Define Ackermann's function Ak(j)A_k(j) and its inverse α(n)\alpha(n) in the CLRS convention, and compute their first values.
  • Prove an O(mlog⁡∗n)O(m \log^* n) bound for union by rank with path compression, and sketch Tarjan's O(m α(n))O(m\,\alpha(n)) analysis with its potential function.
  • State the matching lower bounds with their models of computation, and know the variants: path halving and splitting, union by size, randomized linking, and the linear-time special case.

Four ways to run union-find

LinkingFindWorst-case total for mm operations
naiveplainΘ(mn)\Theta(mn): a path of length n−1n - 1 can form, and every find may walk it
by rank or sizeplainΘ(mlog⁡n)\Theta(m \log n): heights stay ≤⌊log⁡2n⌋\le \lfloor \log_2 n \rfloor
naivepath compressionΘ(n+f (1+log⁡2+f/nn))\Theta(n + f\,(1 + \log_{2 + f/n} n)) for ff finds, so Θ(nlog⁡n)\Theta(n \log n) when f=nf = n
by rank or sizecompression, halving or splittingΘ(m α(m,n))\Theta(m\,\alpha(m, n))
Disjoint-set forests go back to Galler and Fischer (1964). Hopcroft and Ullman (1973) proved O(mlog⁡∗n)O(m \log^* n) for the last row, Tarjan (1975) proved O(m α(m,n))O(m\,\alpha(m, n)), and Tarjan and van Leeuwen (1984) settled every combination of linking rule and compaction method, including the third row. The lesson uses CLRS's one-argument α(n)\alpha(n); the next step explains the two-argument version.
DerivationProof
  1. rank(x)<rank(parent(x))≤rank(root)\mathrm{rank}(x) < \mathrm{rank}(\mathrm{parent}(x)) \le \mathrm{rank}(\mathrm{root})

    (1) A link puts root xx under root yy only if rank(x)≤rank(y)\mathrm{rank}(x) \le \mathrm{rank}(y), and raises yy's rank on a tie, so the inequality is strict afterwards. Ranks change only at roots, and compression moves xx under the root, an ancestor of its old parent, whose rank is larger still.

  2. ∣Ty∣+∣Tx∣≥2r+2r=2r+1\abs{T_y} + \abs{T_x} \ge 2^r + 2^r = 2^{r+1}

    (2) By induction over links. A root's rank grows from rr to r+1r + 1 only when it absorbs another root of rank rr, and both trees have at least 2r2^r nodes; compression moves nodes within a tree and never changes a root's tree.

  3. #{x:rank(x)=r}⋅2r≤n\#\{x : \mathrm{rank}(x) = r\} \cdot 2^r \le n

    (3) When a node xx reaches rank rr, charge it to the 2r2^r or more nodes of its tree at that moment. No node zz is charged by two different rank-rr nodes xx and yy: sets only merge, so at the later of the two moments, say yy's, the root yy has xx in its tree as a non-root of rank at least rr, and (1) would force rank(y)>r\mathrm{rank}(y) > r. So the rank-rr nodes own disjoint groups of size at least 2r2^r:

Ackermann’s function and its inverse

DerivationThe first values
  1. A1(j)=A0(j+1)(j)=2j+1A_1(j) = A_0^{(j+1)}(j) = 2j + 1

    Level 1 adds one, j+1j + 1 times:

  2. A2(j)=A1(j+1)(j)=2j+1(j+1)−1A_2(j) = A_1^{(j+1)}(j) = 2^{j+1}(j + 1) - 1

    Level 2 applies x↦2x+1x \mapsto 2x + 1 to jj, j+1j + 1 times; by induction A1(i)(j)=2i(j+1)−1A_1^{(i)}(j) = 2^i(j + 1) - 1:

  3. A0(1)=2,A1(1)=3,A2(1)=7,A3(1)=A2(2)(1)=A2(7)=28⋅8−1=2047A_0(1) = 2,\quad A_1(1) = 3,\quad A_2(1) = 7,\quad A_3(1) = A_2^{(2)}(1) = A_2(7) = 2^8 \cdot 8 - 1 = 2047

    At j=1j = 1:

  4. A4(1)=A3(2047) ≥ A2(2047)=22048⋅2048−1 > 10619A_4(1) = A_3(2047) \ \ge\ A_2(2047) = 2^{2048} \cdot 2048 - 1 \ >\ 10^{619}

    Level 4 explodes: A4(1)=A3(2)(1)=A3(2047)A_4(1) = A_3^{(2)}(1) = A_3(2047), and already A2(2047)A_2(2047) has more than 600 digits:

  5. α(n)=0 (n≤2),1 (n=3),2 (4≤n≤7),3 (8≤n≤2047),4 (2048≤n≤A4(1))\alpha(n) = 0\ (n \le 2),\quad 1\ (n = 3),\quad 2\ (4 \le n \le 7),\quad 3\ (8 \le n \le 2047),\quad 4\ (2048 \le n \le A_4(1))

    So α\alpha reaches 4 only at n=2048n = 2048 and stays there far beyond the roughly 108010^{80} atoms of the observable universe:

Predict before you look

Using the definition, compute A2(3)A_2(3).

Show the answer

63

A2(3)=A1(4)(3)A_2(3) = A_1^{(4)}(3): apply x↦2x+1x \mapsto 2x + 1 four times to 3, giving 7,15,31,637, 15, 31, 63. The closed form agrees: 24⋅4−1=632^{4} \cdot 4 - 1 = 63.

For comparison, the iterated logarithm log⁡∗n\log^* n counts how many times log⁡2\log_2 must be applied before the value drops to at most 1: log⁡∗2=1\log^* 2 = 1, log⁡∗4=2\log^* 4 = 2, log⁡∗16=3\log^* 16 = 3, log⁡∗65536=4\log^* 65536 = 4 and log⁡∗265536=5\log^* 2^{65536} = 5. It is the inverse of a tower of 2s, which is roughly level 3 of the hierarchy; α\alpha inverts the whole diagonal and grows far more slowly still.

Conventions vary. Tarjan's theorems use a two-argument α(m,n)\alpha(m, n), which shrinks as the ratio m/nm/n grows, and other texts start Ackermann's function from other base cases. All the variants grow at the same absurdly slow rate, and each theorem holds with its own constants.

From log* n to α(n): the analysis

DerivationProof: charge each pointer step to a find or to a node
  1. block j=(bj−1, bj],#blocks≤log⁡∗n+1\text{block } j = (b_{j-1},\ b_j], \qquad \#\text{blocks} \le \log^* n + 1

    Blocks of ranks. Let b0=1b_0 = 1 and bj=2bj−1b_j = 2^{b_{j-1}}, so b=1,2,4,16,65536,…b = 1, 2, 4, 16, 65536, \dots Block 0 holds ranks 0 and 1, and block j≥1j \ge 1 holds the ranks in (bj−1,bj](b_{j-1}, b_j]. Ranks are at most log⁡2n\log_2 n, so only about log⁡∗n\log^* n blocks are ever used.

  2. charges to finds≤m (log⁡∗n+2)\text{charges to finds} \le m\,(\log^* n + 2)

    Charging. A find walks pointers x→parent(x)x \to \mathrm{parent}(x). Charge the step to the find if parent(x)\mathrm{parent}(x) is the root or lies in a different block from xx: ranks increase along the path, so that happens at most log⁡∗n+2\log^* n + 2 times per find. Charge every other step to the node xx.

  3. charges to x≤bj−bj−1<bj\text{charges to } x \le b_j - b_{j-1} < b_j

    Each node pays at most bjb_j times. A node is charged only as a non-root, so its rank, in block jj, is fixed. Each charge is followed by compression, which gives xx a parent of strictly larger rank. After at most bj−bj−1b_j - b_{j-1} charges the parent's rank has left block jj, and from then on every step out of xx is charged to a find.

  4. ∑r>bj−1n2r ≤ n2bj−1=nbj⟹charges to block j≤nbj⋅bj=n\sum_{r > b_{j-1}} \frac{n}{2^r} \ \le\ \frac{n}{2^{b_{j-1}}} = \frac{n}{b_j} \quad\Longrightarrow\quad \text{charges to block } j \le \frac{n}{b_j} \cdot b_j = n

    Each block pays at most nn. By the rank lemma, the nodes whose rank lies in block jj number at most

  5. O(mlog⁡∗n+nlog⁡∗n)=O(mlog⁡∗n)O\big(m \log^* n + n \log^* n\big) = O(m \log^* n)

    Total. At most log⁡∗n+1\log^* n + 1 blocks pay nn each, the finds pay O(mlog⁡∗n)O(m \log^* n), and each union is two finds plus O(1)O(1):

Check your understanding

In this proof, why is a node xx whose rank lies in block jj charged at most about bjb_j times?

  1. Each charge compresses xx's path, which raises xx's own rank by at least 1
  2. Each charge is followed by giving xx a parent of strictly larger rank, and once that rank leaves block jj the step from xx is charged to the find
  3. Each find charges at most one node per block
  4. Block jj contains at most bjb_j nodes
Show the answer

B. Each charge is followed by giving xx a parent of strictly larger rank, and once that rank leaves block jj the step from xx is charged to the find

Ranks of non-roots never change, but the rank of xx's parent rises with every compression that passes through xx. Only bj−bj−1b_j - b_{j-1} values fit in the block, and steps that leave a block are paid by the find.

DerivationProof sketch
  1. 0≤ϕ(x)≤α(n) rank(x)0 \le \phi(x) \le \alpha(n)\,\mathrm{rank}(x)

    Bounded potentials. The ranges of level and iter give 0≤ϕ(x)≤α(n) rank(x)0 \le \phi(x) \le \alpha(n)\,\mathrm{rank}(x), and every node starts with potential 0, so the total potential is never negative and the potential method applies.

  2. ΔΦlink≤α(n)\Delta\Phi_{\text{link}} \le \alpha(n)

    Links. Linking root xx under root yy costs O(1)O(1). Only yy's rank can rise, by 1, which adds at most α(n)\alpha(n) to ϕ(y)\phi(y); the potentials of xx and of yy's other children can only fall, because the ranks of their parents only grow.

  3. rank(root)≥rank(parent(y))≥Ak(rank(y))≥Ak(rank(parent(x)))≥Ak(iter(x)+1)(rank(x))\mathrm{rank}(\mathrm{root}) \ge \mathrm{rank}(\mathrm{parent}(y)) \ge A_k(\mathrm{rank}(y)) \ge A_k(\mathrm{rank}(\mathrm{parent}(x))) \ge A_k^{(\mathrm{iter}(x)+1)}(\mathrm{rank}(x))

    Finds. Let a find visit ss nodes, and let xx (of rank at least 1) be followed higher on the path by some non-root yy with level(y)=level(x)=k\mathrm{level}(y) = \mathrm{level}(x) = k. After compression, xx's parent is the root, and ranks increase along the path, so

  4. c^find≤s−(s−(α(n)+2))=α(n)+2\hat c_{\text{find}} \le s - \big(s - (\alpha(n) + 2)\big) = \alpha(n) + 2

    So iter(x)\mathrm{iter}(x) grows by at least 1, or level(x)\mathrm{level}(x) grows, and either way ϕ(x)\phi(x) drops by at least 1. The nodes without such a yy are the root, the first node if its rank is 0, and the last node of each level, at most α(n)+2\alpha(n) + 2 in all. Scaling the potential so that one unit pays for one pointer step:

Lower bounds, variants and the frontier

VariantWhat changesBound
Union by sizelink by the number of nodes instead of the ranksame Θ(m α(m,n))\Theta(m\,\alpha(m, n))
Path halvingwhile walking up, point every other node at its grandparent: one pass, no stacksame (Tarjan & van Leeuwen, 1984)
Path splittingpoint every node on the path at its grandparentsame (Tarjan & van Leeuwen, 1984)
Randomized linkinglink by random priorities instead of rankssame, in expectation (Goel, Khanna, Larkin & Tarjan, 2014)
Unions known in advancethe union tree is given beforehand, as in offline LCAO(m+n)O(m + n) on the word RAM (Gabow & Tarjan, 1985)
Rollbackundo the last union; no compression allowed, union by rank or size onlyO(log⁡n)O(\log n) per operation, worst case
Rollback is the contest staple for offline dynamic connectivity: a divide and conquer over time adds each edge for an interval of queries and undoes it afterwards. Path compression would make undoing expensive and break the amortized analysis, so it is switched off.

A single operation can still cost Θ(log⁡n)\Theta(\log n) with both heuristics. Blum (1986) showed how to bound every operation by O(log⁡n/log⁡log⁡n)O(\log n / \log\log n) in the worst case. And the inverse Ackermann function is not peculiar to union-find: it reappears in the fastest deterministic MST algorithm (next lesson) and in computational geometry, where the lower envelope of nn line segments in the plane can have Θ(n α(n))\Theta(n\,\alpha(n)) pieces (Davenport–Schinzel sequences).

Key takeaways

  • Union by rank: ranks strictly increase toward the root, a root of rank rr has at least 2r2^r nodes, and at most n/2rn/2^r nodes have rank rr, so ranks and heights are at most ⌊log⁡2n⌋\lfloor \log_2 n \rfloor.
  • A0(1)=2A_0(1) = 2, A1(1)=3A_1(1) = 3, A2(1)=7A_2(1) = 7, A3(1)=2047A_3(1) = 2047 and A4(1)>10619A_4(1) > 10^{619}, so α(n)≤4\alpha(n) \le 4 for every practical nn.
  • With both heuristics, blocks of ranks under a tower of 2s give O(mlog⁡∗n)O(m \log^* n), and Tarjan's level-and-iteration potential gives O(m α(n))O(m\,\alpha(n)); a single find can still cost Θ(log⁡n)\Theta(\log n).
  • Θ(m α(m,n))\Theta(m\,\alpha(m, n)) is tight: Tarjan (1979) for separating pointer machines, Fredman and Saks (1989) for any cell-probe structure. Union by size, path halving or splitting, and randomized linking match it, and unions known in advance allow linear time.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the CLRS convention, what is α(106)\alpha(10^6)?

  1. 3
  2. 4
  3. 5
  4. 20
Show the answer

B. 4

A3(1)=2047<106≤A4(1)A_3(1) = 2047 < 10^6 \le A_4(1), so the least kk with Ak(1)≥106A_k(1) \ge 10^6 is 4.

Question 2

Path compression changes parent pointers but never touches ranks. What does that do to the analysis?

  1. It breaks union by rank, so ranks must be recomputed as heights after every find
  2. Nothing harmful: ranks become upper bounds on heights, and the rank lemmas, which are all the analysis uses, still hold
  3. Ranks become lower bounds on heights, so the log⁡2n\log_2 n height bound fails
  4. Compression must then be limited to paths of length at most α(n)\alpha(n)
Show the answer

B. Nothing harmful: ranks become upper bounds on heights, and the rank lemmas, which are all the analysis uses, still hold

Compression only shortens paths, so a root's rank still bounds its tree's height from above. The rank lemmas, strictly increasing ranks along paths and at most n/2rn/2^r nodes of rank rr, are unaffected, and both the log⁡∗\log^* and the α\alpha analyses are built on them.

Question 3

With union by rank and path compression on n=106n = 10^6 elements, how many pointers can a single find follow in the worst case?

  1. At most α(n)=4\alpha(n) = 4
  2. At most 2, after the first compression
  3. Up to ⌊log⁡2n⌋=19\lfloor \log_2 n \rfloor = 19
  4. Up to n−1n - 1
Show the answer

C. Up to ⌊log⁡2n⌋=19\lfloor \log_2 n \rfloor = 19

The O(α(n))O(\alpha(n)) bound is amortized over the whole sequence, not per operation. A single find can still walk a path as long as the rank bound allows: pairing elements, then pairs of pairs, with no finds in between, builds a tree of height 19, and the first find from its deepest leaf follows 19 pointers.

Question 4

Fredman and Saks (1989) proved an Ω(α(m,n))\Omega(\alpha(m, n)) amortized lower bound per operation for union-find in the cell-probe model. What does it rule out?

  1. Any data structure on a word RAM with O(log⁡n)O(\log n)-bit words that handles arbitrary sequences of unions and finds in o(α(m,n))o(\alpha(m, n)) amortized time per operation
  2. Only pointer-based forests; array tricks or bit parallelism could still beat α\alpha
  3. Any structure with O(log⁡n)O(\log n) worst-case time per operation
  4. Linear total time even when the shape of the unions is known in advance
Show the answer

A. Any data structure on a word RAM with O(log⁡n)O(\log n)-bit words that handles arbitrary sequences of unions and finds in o(α(m,n))o(\alpha(m, n)) amortized time per operation

The cell-probe model charges only for memory accesses and gives all computation away, so its lower bound holds for every word-RAM program, whatever tricks it uses. Pointer machines are the setting of Tarjan's 1979 bound.

Further reading

  • R. E. Tarjan, "Efficiency of a good but not linear set union algorithm," Journal of the ACM 22(2) (1975), 215–225.
  • R. E. Tarjan, "A class of algorithms which require nonlinear time to maintain disjoint sets," Journal of Computer and System Sciences 18(2) (1979), 110–127.
  • R. E. Tarjan & J. van Leeuwen, "Worst-case analysis of set union algorithms," Journal of the ACM 31(2) (1984), 245–281.
  • M. L. Fredman & M. E. Saks, "The cell probe complexity of dynamic data structures," Proceedings of the 21st ACM Symposium on Theory of Computing (1989), 345–354.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 19.