Module contents
Lesson 11 of 33Core 90 min

Union-find and the inverse Ackermann function

Analyze union-find, rank and path compression, inverse Ackermann bounds, and incremental and offline connectivity.

After this lesson you can

  • Implement union-find iteratively with union by size and path compression.
  • Prove union by rank bounds height by log₂ n.
  • Prove the O(m log* n) bound and explain the idea behind the α(n) bound.
  • Solve incremental and offline connectivity problems with union-find.
  • Recognize when union-find does not apply, such as online edge deletion.

Before you start

Motivation: a partition that only merges

A graph grows one edge at a time and at every moment must answer a question: are uu and vv in the same connected component? Recomputing components by depth-first search after every edge costs O(n+m)\bigO(n + m) per query, and with 10610^6 edges takes 101210^{12} steps. But the question has special structure: components only merge, never split, allowing a data structure whose operation costs practically a constant.

The same pattern appears in places that seem unrelated:

  • Percolation and image processing. A grid of pixels or cells fills up and we need to know which cells form a connected region, or whether a region touches opposite boundaries. We will see this with a Monte Carlo simulation and binary-image component labeling.
  • Minimum spanning trees. Kruskal’s algorithm (graph lesson) traverses edges by weight and needs to know whether an edge closes a cycle, meaning whether its endpoints are already connected.
  • Unification and congruence closure. SMT solvers (congruence closure) and type-inference unification maintain equivalence classes of terms as they are identified.
  • Clustering. Hierarchical clustering’s single linkage is Kruskal in disguise, and grouping near-duplicate pairs after locality-sensitive hashing is a chain of unions.

The lesson aims to understand, with proof, why two one-line heuristics (linking by rank and path compression) bring amortized cost to O(α(n))\bigO(\alpha(n)), where α\alpha is the inverse Ackermann function: a function not exceeding 4 while nn is a number that fits in the universe. Also understand the guarantee’s limits: it is neither strictly constant nor applicable when edges must be deleted online.

The problem and first analysis

A partition of a set XX is a family of nonempty disjoint subsets whose union is XX; it is equivalent to an equivalence relation on XX whose classes are the blocks. Merging two blocks is equivalent to adding a pair to the relation and taking closure. For the growing-graph problem, the class of vv is its connected component (paths and connectivity) and adding edge {u,v}\{u, v\} merges the classes of uu and vv.

The two simplest solutions fail on opposite sides. An array etiqueta[x] storing each element’s representative gives find in O(1)\bigO(1), but union must relabel a whole block: O(n)\bigO(n). An uncareful tree links two roots in O(1)\bigO(1), but its find can cost O(n)\bigO(n). The first analysis balancing both uses linked lists with weighted union: each block is a list whose nodes store its representative, and union relabels the shorter list’s elements and concatenates it to the longer.

Proof

find and make_set cost O(1)\bigO(1), and each union costs O(1)\bigO(1) plus the number of relabeled elements. Fix an element xx: whenever relabeled, its block belonged to the shorter union list, so xx‘s block at least doubles. Since no block exceeds nn elements, xx is relabeled at most log⁡2n\log_2 n times. Summing over nn elements gives at most nlog⁡2nn \log_2 n relabelings. ■\blacksquare

∎

This is an amortized bound in the sense of the previous amortized-analysis lesson: a particular union can move n/2n/2 elements, but the total is bounded. The key idea, “move the smaller”, will return in another guise. One jump remains: from nlog⁡nn \log n total to nearly nn.

Pointer forests

Galler and Fischer (1964) proposed storing each block as a rooted tree (rooted tree) where each node points to its parent and the root points to itself. The representative is the root. The entire structure is an array padre:

  • find(x): follow pointers upward to the root.
  • union(x, y): find the two roots a=find(x)a = \mathrm{find}(x) and b=find(y)b = \mathrm{find}(y) and, if different, link one below the other (padre[a] = b).

Without further care the tree can degenerate: union(0,1), union(1,2), ... with the link “hang the first root under the second” builds a chain of nn nodes and the next find(0) follows n−1n - 1 pointers. We measure operation cost as the number of pointers followed by find.

InteractiveThe union-find forest
Current forest (without rank, no compression); each node points to its parent0123456789101112131415Same sequence for each combination: pointers followed (final height)none90 (15)rank only14 (1)compression only20 (1)rank and compression14 (1)
Click a node
Path compression
Loaded sequence
21 of 21
Elements
Sets1
Forest height15
Maximum height reached15
Pointers followed (total)90
Last operation cost15
Mean cost per operation4.29
find(0): 15 pointers followed.
Initial state: a chain of 16 nodes and six searches from the leaf, without heuristics (90 pointers followed). In ‘Union two’ mode click two nodes to merge; in ‘Find’, one. Enable union by rank: the same history produces a forest of height 1. Disable it and try compression alone: the first search pays for 15 pointers and the others cost 1. Then load ‘Binomial’ with compression only: this sequence forces logarithmic height cost in every round. Slide ‘Applied operations’ to see how the forest was built and compare the four combinations in the bars below.

There are two independent improvements, and the figure shows what each fixes. The first prevents trees from growing tall during linking; the second repairs tall trees when traversed.

Union by rank and size

Without compression, a node’s rank is exactly its subtree height; with compression it becomes a surviving upper bound on that height: compression shortens trees but does not touch rank. With rank, the tallest tree grows only when two equally tall trees merge, requiring the node count to double.

Proof

Induct on the number of links to show tam(x)≥2rango(x)\mathrm{tam}(x) \ge 2^{\mathrm{rango}(x)} for every xx and that the height of xx (maximum distance to a leaf in its subtree) is at most rango(x)\mathrm{rango}(x). Initially tam=1=20\mathrm{tam} = 1 = 2^0 and height is 0. Consider a link of root bb below root aa with rango(b)≤rango(a)\mathrm{rango}(b) \le \mathrm{rango}(a).

  • If rango(b)<rango(a)\mathrm{rango}(b) < \mathrm{rango}(a), the rank of aa does not change, its size grows and its height becomes max⁡(ha,hb+1)≤rango(a)\max(h_a, h_b + 1) \le \mathrm{rango}(a) because hb+1≤rango(b)+1≤rango(a)h_b + 1 \le \mathrm{rango}(b) + 1 \le \mathrm{rango}(a).
  • If ranks both equal rr, the rank of aa becomes r+1r + 1, its size at least 2r+2r=2r+12^r + 2^r = 2^{r+1} and its height max⁡(ha,hb+1)≤r+1\max(h_a, h_b + 1) \le r + 1.

Other nodes change neither rank nor subtree. Since 2rango(x)≤tam(x)≤n2^{\mathrm{rango}(x)} \le \mathrm{tam}(x) \le n, rango(x)≤log⁡2n\mathrm{rango}(x) \le \log_2 n follows, as does the height bound. ■\blacksquare

∎

Union by size gives the same result with an even more direct proof: a node drops one level only when its tree joins another at least as large, so its tree doubles, and this can happen at most log⁡2n\log_2 n times. With rank or size, any sequence of mm operations costs O(mlog⁡n)\bigO(m \log n), and the bound is attained: merging equal-sized binomial trees yields a tree of exact height log⁡2n\log_2 n.

Path compression

There is another way to exploit the fact that find already traverses a path to the root: make that path shorter next time.

The standard version, full compression, makes two passes (one to find the root, one to redirect). Two one-pass variants need neither recursion nor a second pass and are therefore used in practice:

  • Path splitting: each visited node points to its grandparent, and traversal continues through the original parent.
  • Path halving: each visited node points to its grandparent and traversal continues through the grandparent, skipping alternate nodes.

All three have the same asymptotic bounds shown below. Try them in the previous figure: they change forest shape (full compression flattens it at once, the other two flatten it in halves), but not cost order of magnitude.

Compression alone. Without union by rank, compression already helps greatly: in the figure’s chain, the first search pays n−1n - 1 pointers and subsequent searches one. But it is not enough. Fischer (1972) and Tarjan and van Leeuwen (1984) showed that with arbitrary linking and compression, worst-case cost is Θ(mlog⁡1+m/nn)\Theta(m \log_{1 + m/n} n); for m=Θ(n)m = \Theta(n) it is Θ(nlog⁡n)\Theta(n \log n). The extreme example is a binomial tree BkB_k (a node B0B_0; BkB_k is a root with children B0,…,Bk−1B_0, \dots, B_{k-1}, with 2k2^k nodes and depth kk), with a new root added above and a search from the deepest leaf: compression reorganizes the tree but leaves it shaped like an BkB_k again (with an extra leaf or so), so the next new root again creates a path of length k+1k + 1. Each round costs k+1k + 1 and the tree hardly changes; you will prove this in an exercise and the figure reproduces it with the ‘Binomial’ sequence.

The heuristics complement each other: rank prevents tall trees from the start and compression makes heavily traversed paths cheap. Tarjan’s theorem says together they give amortized O(α(n))\bigO(\alpha(n)). The route there passes through an intermediate, easier-to-prove bound that is already almost linear.

The O(mlog⁡∗n)\bigO(m \log^* n) bound

The iterated logarithm log⁡∗n\log^* n is the number of times log⁡2\log_2 must be applied to reach 11 or less:

log⁡∗n={0si n≤1,1+log⁡∗(log⁡2n)si n>1.\log^* n = \begin{cases} 0 & \text{si } n \le 1, \\ 1 + \log^*(\log_2 n) & \text{si } n > 1. \end{cases}

It grows so slowly that log⁡∗65536=4\log^* 65536 = 4 (because 65536→16→4→2→165536 \to 16 \to 4 \to 2 \to 1) and log⁡∗(265536)=5\log^* (2^{65536}) = 5. The proof uses three rank properties valid with any mixture of compressions, because compression does not touch ranks.

Proof

(1) Rank changes only in a root receiving a child of the same rank. (2) On linking, root bb hanging under aa has lower rank than aa or, if equal, aa‘s rank increases by 1, so in both cases rango(a)>rango(b)\mathrm{rango}(a) > \mathrm{rango}(b). Compression redirects node vv to root rr of the path (or, in splitting and halving, to its grandparent), a proper ancestor of vv‘s old parent and, by monotonicity along that path, of strictly higher rank; if the parent was already root, nothing changes. (3) Reason about the link forest that would result ignoring compressions: its subtrees are those of the preceding theorem and every node of rank rr has at least 2r2^r descendants. Two nodes of the same rank cannot be ancestors of one another (by strict monotonicity), so their subtrees are disjoint and at most n/2rn / 2^r nodes have rank rr. Summing the geometric series gives ∑s≥rn/2s=n/2r−1\sum_{s \ge r} n/2^s = n/2^{r-1}. ■\blacksquare

∎

Now group ranks into blocks whose lengths grow as a power tower. Let t(0)=1t(0) = 1 and t(j+1)=2t(j)t(j+1) = 2^{t(j)}: 1,2,4,16,65536,265536,…1, 2, 4, 16, 65536, 2^{65536}, \dots. Block 00 contains ranks {0,1}\{0, 1\} and block j≥1j \ge 1 contains ranks t(j−1)<r≤t(j)t(j-1) < r \le t(j): {2}\{2\}, {3,4}\{3, 4\}, {5,…,16}\{5, \dots, 16\}, {17,…,65536}\{17, \dots, 65536\}, etc. Since maximum rank is ≤log⁡2n\le \log_2 n, the number BB of blocks used satisfies B≤log⁡∗nB \le \log^* n.

Proof

Each union consists of two find and O(1)\bigO(1) of linking, so it suffices to bound pointers followed by the m′≤2mm' \le 2m find. In one find, let x=v0,v1,…,vLx = v_0, v_1, \dots, v_L be the path to the root. Each pointer vi→vi+1v_i \to v_{i+1} (i<Li < L) is charged as follows:

  • Type C: if vi+1v_{i+1} is the root, charge it to find. This is one pointer per search.
  • Type A: if vi+1v_{i+1} is not root and is in a higher block than viv_i, charge it to find. Ranks increase along the path, so block index does not decrease and this occurs at most B−1B - 1 times per search.
  • Type B: if vi+1v_{i+1} is not root and is in the same block as viv_i, charge it to node viv_i.

A and C charges total at most BB per search, ≤m′B\le m' B overall. For B charges, consider node vv in block jj. Whenever charged, its parent is not root and compression redirects it to the root, whose rank is strictly higher than its previous parent’s. While the parent stays in block jj, this can repeat at most once per block rank above its own: fewer than t(j)−t(j−1)t(j) - t(j-1) times. Once its parent moves to a higher block, all future charges to vv are type A. Thus:

  • Block 00: at most nn nodes, each receiving at most 1 B charge (rank 0 to rank 1): ≤n\le n.
  • Block 11 (rank {2}\{2\}) cannot have B charges: parent rank is strictly greater.
  • Block j≥2j \ge 2: by the lemma at most n/2t(j−1)n / 2^{t(j-1)} nodes have rank >t(j−1)> t(j-1) and each receives fewer than t(j)−t(j−1)<2t(j−1)t(j) - t(j-1) < 2^{t(j-1)} B charges, so the whole block receives fewer than nn.

B charges therefore total at most nBnB, and total cost is ≤m′B+nB=O((m+n)log⁡∗n)\le m'B + nB = \bigO((m + n) \log^* n). ■\blacksquare

∎

Everything needed from this proof is in the next figure, which actually counts charges of each type on a real forest: number of nodes of each rank (bars, logarithmic scale) against the lemma’s n/2rn/2^r bound, and each block’s type B charges (solid bars) against its bound (outline). In the tournament the rank lemma is attained up to a factor of 2, but charges remain several times below their bounds in both modes: the proof is worst-case and does not predict typical cost.

InteractiveRank blocks and charging
Nodes per rank (log scale); diamond: n/2ʳ bound1101001.0 k0123456789101112rank r (color = block)Type B charges per block: measured (solid) and nodes × width bound (outline)block 0: ranks 0 to 1, 3.1 k nodes657 / 3.1 kblock 1: rank 2, 512 nodes0 / 0block 2: ranks 3 to 4, 384 nodes128 / 384block 3: ranks 5 to 12 (and higher), 128 nodes120 / 1.4 kn = 4.1 k
Elements
Union method
Subsequent finds
Blocks in use4
Maximum rank12
Pointers followed7.3 k
Bound m′B+nBm'B + nB66 k
Across 12 k finds (including those in unions), 7.3 k pointers were followed: 0.59 per find. The theorem allows up to 66 k, with BB = 4 blocks in use and m′m' finds. Charge A: 2.3 k (bound 37 k); charge B: 905 (bound 4.9 k); charge C: 4.1 k (bound 12 k).
Run the proof's accounting on a real forest. With ‘Tournament’ the forest is a union of binomial trees: node count per rank halves at each step, parallel to bound n/2rn/2^r (diamonds) and exactly half of it except at maximum rank, whose single node meets it. Each color is a rank block; the last is wider than all preceding ones. Raise nn from 256 to 65536: maximum rank doubles (8 to 16) and block count stays 4. Switch to ‘Random’: ranks are much smaller (with 65536 elements the maximum is around 7), and both type B charges and total pointers remain several times below their bounds.

Ackermann’s function and its inverse

The log⁡∗n\log^* n bound can improve because block reasoning has a weak point: a factor is lost within a block and can be recovered using finer, recursively refined blocks. After Tarjan’s work (1975), the result is a function growing more slowly than any iteration of log⁡∗\log^*, defined using the Ackermann hierarchy.

It is a staircase. A1(j)=2j+1A_1(j) = 2j + 1 and A2(j)=2j+1(j+1)−1A_2(j) = 2^{j+1}(j+1) - 1 have closed forms, and with them

A0(1)=2,A1(1)=3,A2(1)=7,A3(1)=A2(A2(1))=A2(7)=2047.A_0(1) = 2, \qquad A_1(1) = 3, \qquad A_2(1) = 7, \qquad A_3(1) = A_2(A_2(1)) = A_2(7) = 2047.

The next step no longer fits anywhere: A4(1)=A3(2047)=A2(2048)(2047)A_4(1) = A_3(2047) = A_2^{(2048)}(2047). Since A2(j)≥2jA_2(j) \ge 2^j, this quantity is at least a tower of 20482048 twos, 22⋅⋅22^{2^{\cdot^{\cdot^{2}}}}. Therefore α(n)=0\alpha(n) = 0 for n≤2n \le 2, 11 for n=3n = 3, 22 for 4≤n≤74 \le n \le 7, 33 for 8≤n≤20478 \le n \le 2047 and 44 for 2048≤n≤A4(1)2048 \le n \le A_4(1). For any nn that can be written, copied or counted with atoms, α(n)≤4\alpha(n) \le 4. Literature also uses a two-argument form α(m,n)\alpha(m, n), depending on density m/nm/n and smaller still when m≫nm \gg n; for m≥n≥3m \ge n \ge 3, α(n)\alpha(n) is a valid upper bound on it.

InteractiveHow slowly α(n) grows
Staircase: α(n) is the first rung k with Aₖ(1) ≥ nk = 0A₀(1) = 2α = 0 if n ≤ 2k = 1A₁(1) = 3α = 1 if n = 3k = 2A₂(1) = 7α = 2 if 4 ≤ n ≤ 7k = 3A₃(1) = 2047α = 3 if 8 ≤ n ≤ 2047k = 4A₄(1) = a tower of at least 2048 twosα = 4 if 2048 ≤ n ≤ A₄(1)Four functions of n (logarithmic vertical axis; horizontal axis: digits of n)1101001000110¹⁰⁰10²⁰⁰10³⁰⁰10⁴⁰⁰log₂ nlog₂ log₂ nlog* nα(n)
10^80
log⁡2n\log_2 n265.8
log⁡2log⁡2n\log_2 \log_2 n8.05
log⁡∗n\log^* n5
α(n)\alpha(n)4
With nn = 10⁸⁰, α(n)=4\alpha(n) = 4. To reach 5 requires n>A4(1)n > A_4(1), a tower of at least 2048 twos: a number with vastly more digits than atoms in the observable universe.
Choose size nn from units to 102500010^{25000}, beyond 265536≈10197282^{65536} \approx 10^{19728} (the right button). Past that number, log⁡∗n\log^* n rises to 6 and α(n)\alpha(n) stays at 4. The upper staircase marks the step kk containing nn, and the chart compares four functions on a logarithmic vertical axis: log⁡2n\log_2 n climbs without bound, log⁡2log⁡2n\log_2 \log_2 n grows slowly, log⁡∗n\log^* n jumps from 3 to 5 and α(n)\alpha(n) goes only from 3 to 4. With n=1080n = 10^{80} (order of magnitude of atoms in the observable universe), log⁡∗n=5\log^* n = 5 and α(n)=4\alpha(n) = 4; α(n)=5\alpha(n) = 5 requires more than a tower of 2048 twos.

The full proof takes several pages (CLRS, chapter 19 of the fourth edition, section “Analysis of union by rank with path compression”). The idea is a potential refining blocks into α(n)\alpha(n) levels. For a non-root node xx of rank ≥1\ge 1, with parent pp, define:

δ(x)=max⁡{k:rango(p)≥Ak(rango(x))},ι(x)=max⁡{i:rango(p)≥Aδ(x)(i)(rango(x))}.\delta(x) = \max\{k : \mathrm{rango}(p) \ge A_k(\mathrm{rango}(x))\}, \qquad \iota(x) = \max\{i : \mathrm{rango}(p) \ge A_{\delta(x)}^{(i)}(\mathrm{rango}(x))\}.

The level δ(x)\delta(x) says how high on the Ackermann staircase the parent’s rank is relative to the child’s, and iteration ι(x)\iota(x) says how many times AδA_\delta was applied. Since rango(p)≥rango(x)+1=A0(rango(x))\mathrm{rango}(p) \ge \mathrm{rango}(x) + 1 = A_0(\mathrm{rango}(x)) and rango(p)≤log⁡2n<Aα(n)(1)\mathrm{rango}(p) \le \log_2 n < A_{\alpha(n)}(1), we have 0≤δ(x)≤α(n)−10 \le \delta(x) \le \alpha(n) - 1 and 1≤ι(x)≤rango(x)1 \le \iota(x) \le \mathrm{rango}(x). The potential of xx is φ(x)=α(n) rango(x)\varphi(x) = \alpha(n)\,\mathrm{rango}(x) if xx is root or has rank 00, and φ(x)=(α(n)−δ(x)) rango(x)−ι(x)\varphi(x) = (\alpha(n) - \delta(x))\,\mathrm{rango}(x) - \iota(x) otherwise. Since ∑xrango(x)≤∑rr n/2r=2n\sum_x \mathrm{rango}(x) \le \sum_r r\, n/2^r = 2n, total potential is at most 2n α(n)2n\,\alpha(n).

The heart of the proof is the following lemma, which can be proved from what we already have.

Proof

Let i=ι(x)i = \iota(x) before compression. Since yy is an ancestor of p(x)p(x) or is p(x)p(x), rango(y)≥rango(p(x))≥Ak(i)(rango(x))\mathrm{rango}(y) \ge \mathrm{rango}(p(x)) \ge A_k^{(i)}(\mathrm{rango}(x)). Since δ(y)=k\delta(y) = k, rango(p(y))≥Ak(rango(y))\mathrm{rango}(p(y)) \ge A_k(\mathrm{rango}(y)). After compression the new parent of xx is the root, whose rank is ≥rango(p(y))\ge \mathrm{rango}(p(y)). Since AkA_k is increasing,

rango(nuevo padre de x)≥Ak(rango(y))≥Ak(Ak(i)(rango(x)))=Ak(i+1)(rango(x)).\mathrm{rango}(\text{nuevo padre de } x) \ge A_k(\mathrm{rango}(y)) \ge A_k\bigl(A_k^{(i)}(\mathrm{rango}(x))\bigr) = A_k^{(i+1)}(\mathrm{rango}(x)).

There are two cases. If δ(x)\delta(x) remains kk, then ι(x)≥i+1\iota(x) \ge i + 1 and φ(x)\varphi(x) falls by at least 1. If δ(x)\delta(x) rises, the new parent rank reaches Ak(rango(x)+1)(rango(x))=Ak+1(rango(x))A_k^{(\mathrm{rango}(x)+1)}(\mathrm{rango}(x)) = A_{k+1}(\mathrm{rango}(x)) or more, and with new level δ′≥k+1\delta' \ge k + 1 and new iteration ι′≥1\iota' \ge 1, φ(x)=(α−δ′) rango(x)−ι′≤(α−k−1) rango(x)−1\varphi(x) = (\alpha - \delta')\,\mathrm{rango}(x) - \iota' \le (\alpha - k - 1)\,\mathrm{rango}(x) - 1, whereas before it was (α−k) rango(x)−i≥(α−k−1) rango(x)(\alpha - k)\,\mathrm{rango}(x) - i \ge (\alpha - k - 1)\,\mathrm{rango}(x) because i≤rango(x)i \le \mathrm{rango}(x): it also falls by at least 1. ■\blacksquare

∎

Now count. On a path of ss nodes, these cannot decrease potential: the root, the rank-00 node (at most one by rank monotonicity), and at most the last node of each level, of which there are at most α(n)\alpha(n). Every other path node reduces potential by at least 1. Amortized search cost is s+ΔΦ≤s−(s−α(n)−2)=α(n)+2s + \Delta\Phi \le s - (s - \alpha(n) - 2) = \alpha(n) + 2. Two full-proof details remain: compression never increases any node’s potential, and linking two roots changes total potential by O(α(n))\bigO(\alpha(n)). Then mm operations cost O(m α(n))\bigO(m\,\alpha(n)) plus initial potential, 00 when starting from isolated nodes.

Top-down analysis. Seidel and Sharir (2005) gave a proof that changes direction. Rather than construct a decreasing potential, they start from a monotone-rank forest and mm compressions and define maximum cost C(m,n,r)C(m, n, r) of compressing mm paths in an nn-node forest with rr ranks. Cut the forest at rank ss: low trees (ranks below ss) and the high forest (ranks at least that). Each compression path splits into a low segment and, if it reaches it, a high segment. High segments form an instance of the same problem with r−sr - s ranks, at most mm compressions and many fewer nodes (by the rank lemma, at most n/2s−1n/2^{s-1}), so a coarse bound suffices. Paths that do not leave low trees form another instance with only ss ranks. In paths that rise, the low segment is charged directly: 11 for the edge crossing into the high forest and 11 per low node which, upon compression, becomes a child of the high forest, something each node does once. The resulting recurrence has form C(m,n,r)≤C(malto,nalto,r−s)+C(mbajo,nbajo,s)+malto+nbajoC(m, n, r) \le C(m_{\text{alto}}, n_{\text{alto}}, r - s) + C(m_{\text{bajo}}, n_{\text{bajo}}, s) + m_{\text{alto}} + n_{\text{bajo}}. Applied repeatedly with cuts chosen by the Ackermann staircase steps, each pass improves the preceding bound by one hierarchy level, and the number of passes needed is on the order of α(n)\alpha(n). This is an outline: the recurrence is not solved here, and details are in the paper. The same method also gives Tarjan and van Leeuwen’s O(mlog⁡1+m/nn)\bigO(m \log_{1+m/n} n) upper bound for compression without rank.

Can it be improved? No: the bound is optimal. Tarjan (1979) proved that in the pointer-machine model any separable algorithm (those that, like this one, link only nodes of the same set) needs Ω(m α(m,n))\Omega(m\,\alpha(m, n)), and Fredman and Saks (1989) proved amortized Ω(α(m,n))\Omega(\alpha(m, n)) per operation in the cell-probe model for any structure, with log⁡n\log n-bit words. Thus α\alpha is not an artifact of analysis: it is the problem’s true cost.

Implementation from scratch

First, the complete structure with three compression variants and a pointer counter, and the figure’s experiment with larger nn: a random sequence, a chain with repeated searches, and the binomial sequence. Everything is iterative: recursive find overflows on a long path before compression can act (by default, Python gives up at 1000 levels).

[ ]Instrumented union-find: four combinationsBrowser
import random

class UnionFind:
    """Union-find con heurísticas elegibles y contador de punteros seguidos (aristas de los caminos de búsqueda)."""

    def __init__(self, n, por_tamano=True, compresion="completa"):
        self.padre = list(range(n))
        self.tam = [1] * n
        self.por_tamano = por_tamano
        self.compresion = compresion      # "ninguna", "completa" o "mitad"
        self.punteros = 0                 # coste acumulado
        self.mayor = 0                    # coste de la búsqueda individual más cara

    def buscar(self, x):
        p = self.padre
        pasos = 0
        if self.compresion == "mitad":    # reducción a la mitad: un solo recorrido, sin recursión
            while p[x] != x:
                papa = p[x]
                abuelo = p[papa]
                pasos += 1 if abuelo == papa else 2
                p[x] = abuelo
                x = abuelo
            raiz = x
        else:
            raiz = x
            while p[raiz] != raiz:
                raiz = p[raiz]
                pasos += 1
            if self.compresion == "completa":
                while p[x] != raiz:       # segunda pasada: todos los del camino apuntan a la raíz
                    siguiente = p[x]
                    p[x] = raiz
                    x = siguiente
        self.punteros += pasos
        self.mayor = max(self.mayor, pasos)
        return raiz

    def unir(self, x, y):
        a, b = self.buscar(x), self.buscar(y)     # se unen las RAÍCES, no los elementos
        if a == b:
            return False
        if self.por_tamano and self.tam[a] > self.tam[b]:
            a, b = b, a                           # la raíz del árbol menor cuelga de la del mayor
        self.padre[a] = b                         # con por_tamano=False, la de x cuelga siempre de la de y
        self.tam[b] += self.tam[a]
        return True

    def altura(self):
        def prof(x):
            d = 0
            while self.padre[x] != x:
                x = self.padre[x]
                d += 1
            return d
        return max(prof(x) for x in range(len(self.padre)))

def aleatoria(n, m, semilla=0):
    r = random.Random(semilla)
    return [("u", r.randrange(n), r.randrange(n)) if r.random() < 0.5 else ("f", r.randrange(n)) for _ in range(m)]

def cadena(n, repeticiones):
    ops = [("u", i, i + 1) for i in range(n - 1)]       # con enlace ingenuo, forma una cadena
    return ops + [("f", 0)] * repeticiones

def binomial(k):
    """Secuencia de Fischer / Tarjan y van Leeuwen para la compresión sin rango (2^k nodos binomiales + 2^k rondas)."""
    n = 2 ** (k + 1)
    uf = UnionFind(n, por_tamano=False, compresion="completa")
    ops, nivel = [], list(range(2 ** k))
    while len(nivel) > 1:                               # árbol binomial B_k por fusiones de pares
        siguiente = []
        for i in range(0, len(nivel), 2):
            ops.append(("u", nivel[i], nivel[i + 1]))
            uf.unir(nivel[i], nivel[i + 1])
            siguiente.append(nivel[i + 1])
        nivel = siguiente
    raiz = nivel[0]
    for nuevo in range(2 ** k, n):                      # raíz nueva encima y búsqueda desde la hoja más profunda
        ops.append(("u", raiz, nuevo))
        uf.unir(raiz, nuevo)
        raiz = nuevo
        prof = {}
        def d(x):
            if x not in prof:
                prof[x] = 0 if uf.padre[x] == x else 1 + d(uf.padre[x])
            return prof[x]
        hoja = max(range(nuevo + 1), key=d)
        ops.append(("f", hoja))
        uf.buscar(hoja)
    return n, ops

def ejecutar(n, ops, **kw):
    uf = UnionFind(n, **kw)
    for op in ops:
        if op[0] == "u":
            uf.unir(op[1], op[2])
        else:
            uf.buscar(op[1])
    return uf

CONFIGS = [("ninguna", dict(por_tamano=False, compresion="ninguna")),
           ("solo tamaño", dict(por_tamano=True, compresion="ninguna")),
           ("solo compresión", dict(por_tamano=False, compresion="completa")),
           ("tamaño + compresión", dict(por_tamano=True, compresion="completa")),
           ("tamaño + mitad", dict(por_tamano=True, compresion="mitad"))]

n_b, ops_b = binomial(8)
escenarios = [("aleatoria", 4096, aleatoria(4096, 8192)),
              ("cadena y búsquedas", 2048, cadena(2048, 20)),
              ("binomial (adversaria)", n_b, ops_b)]
for nombre, n, ops in escenarios:
    print(f"{nombre}: n = {n}, {len(ops)} operaciones")
    for etiqueta, kw in CONFIGS:
        uf = ejecutar(n, ops, **kw)
        print(f"   {etiqueta:22s} punteros/op = {uf.punteros / len(ops):8.2f}   búsqueda más cara = {uf.mayor:5d}   altura final = {uf.altura()}")

In the random sequence, without heuristics mean cost is tens of pointers per operation (with heights of hundreds), and with rank and compression it drops below one (many operations land on nodes already pointing to the root). In the chain the two halves are separate: size only prevents the chain from the start, whereas compression only lets it form and pays for one 20472047-pointer search, after which all cost 11. The binomial sequence separates “compression only” from “size + compression”: the former pays k+1=9k + 1 = 9 pointers per search each round (mean 33 pointers per operation, three times the latter), and the latter leaves a flat tree (final height 11). With n=220n = 2^{20} the difference would grow logarithmically, but each cell must finish in a few seconds.

Second exercise: Monte Carlo percolation and image component labeling. Here the minimal structure (size plus path splitting) matters, along with comparing its labeling partition with scipy.ndimage.label.

[ ]Monte Carlo percolation and component labelingBrowser
import random
import numpy as np
from scipy import ndimage

class DSU:
    """Versión mínima: unión por tamaño y división de caminos, iterativa."""
    def __init__(self, n):
        self.p = list(range(n))
        self.tam = [1] * n
        self.pasos = 0

    def buscar(self, x):
        p = self.p
        while p[x] != x:
            p[x], x = p[p[x]], p[x]       # cada nodo apunta a su abuelo
            self.pasos += 1
        return x

    def unir(self, x, y):
        a, b = self.buscar(x), self.buscar(y)
        if a == b:
            return False
        if self.tam[a] < self.tam[b]:
            a, b = b, a
        self.p[b] = a
        self.tam[a] += self.tam[b]
        return True

def percolar(n, rng):
    """Abre celdas al azar hasta que el techo conecta con el suelo. Devuelve (fracción abierta, pasos de puntero por apertura)."""
    techo, suelo = n * n, n * n + 1
    d = DSU(n * n + 2)
    orden = list(range(n * n))
    rng.shuffle(orden)
    abierta = [False] * (n * n)
    for k, c in enumerate(orden, 1):
        abierta[c] = True
        i, j = divmod(c, n)
        if i == 0:
            d.unir(c, techo)
        if i == n - 1:
            d.unir(c, suelo)
        for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            a, b = i + di, j + dj
            if 0 <= a < n and 0 <= b < n and abierta[a * n + b]:
                d.unir(c, a * n + b)
        if d.buscar(techo) == d.buscar(suelo):
            return k / (n * n), d.pasos / k
    return 1.0, d.pasos / (n * n)

rng = random.Random(2024)
for n in (16, 32, 48):
    res = [percolar(n, rng) for _ in range(30)]
    umbral = np.array([r[0] for r in res])
    print(f"n = {n:2d}: umbral medio {umbral.mean():.3f} ± {umbral.std(ddof=1) / np.sqrt(len(umbral)):.3f}   pasos por apertura {np.mean([r[1] for r in res]):.2f}")

def etiquetar(imagen):
    """Etiquetado de componentes conexas (4 vecinos) con union-find: una pasada para unir, otra para nombrar."""
    h, w = imagen.shape
    d = DSU(h * w)
    for i in range(h):
        for j in range(w):
            if imagen[i, j]:
                if i > 0 and imagen[i - 1, j]:
                    d.unir(i * w + j, (i - 1) * w + j)
                if j > 0 and imagen[i, j - 1]:
                    d.unir(i * w + j, i * w + j - 1)
    nombres, salida = {}, np.zeros((h, w), dtype=int)
    for i in range(h):
        for j in range(w):
            if imagen[i, j]:
                salida[i, j] = nombres.setdefault(d.buscar(i * w + j), len(nombres) + 1)
    return salida, len(nombres)

img = np.random.default_rng(5).random((64, 64)) < 0.55
mia, k_mia = etiquetar(img)
ref, k_ref = ndimage.label(img)            # estructura por defecto: 4 vecinos
iguales = all(len(set(ref[mia == e])) == 1 for e in range(1, k_mia + 1))    # misma partición, quizá con otros nombres
print(f"componentes: union-find {k_mia}, scipy.ndimage.label {k_ref}, misma partición: {k_mia == k_ref and iguales}")

Mean grid threshold is around 0.590.59 for all three sizes, compatible with 0.5930.593 (with 3030 grids per size, standard error is between 0.0040.004 and 0.0110.011: this is a statistical estimate, not an exact value), and each opening costs about 3.43.4 pointers (counting the percolation query) without growing with nn. Labeling agrees with SciPy in component count and partition: only label names differ.

Applications

Kruskal and cycle detection

Kruskal’s algorithm visits edges in increasing weight and retains each that does not close a cycle with those already chosen: that is, one joining two distinct components. This is union-find directly: if union(u, v): añadir arista. Cost is sorting, O(mlog⁡m)\bigO(m \log m), plus O(m α(n))\bigO(m\,\alpha(n)) for unions. The same idea detects cycles in an undirected graph: an edge whose endpoints are already in the same set closes a cycle. It does not work for directed graphs: in a→ba \to b, b→cb \to c, a→ca \to c all three nodes end in the same set but there is no directed cycle. Weak connectivity ignores edge direction, which directed cycles require (use depth-first search with colors or topological ordering instead).

Percolation

A grid n×nn \times n whose cells open independently with probability pp percolates if an open-cell path connects top to bottom. There is a sharp threshold: for large nn, percolation probability changes from ≈0\approx 0 to ≈1\approx 1 around pc≈0.5927p_c \approx 0.5927 (Newman and Ziff, 2000, estimated 0.5927460.592746 for square-lattice site percolation). To simulate it nothing must be recomputed after each opening: add two virtual nodes, ceiling and floor, linked to every open cell in the first and last rows, and simply ask whether find(techo) == find(suelo). Each opening makes at most four unions with open neighbors.

InteractivePercolation on a grid
Top (virtual node)Bottom (virtual node)closedopenconnected to topconnects top and bottomPointers followed per opening (running mean) by heuristic012250432 open cellsnonerank onlycompression onlyrank and compressionThreshold observed in 100 grids of 24 × 240.50.60.7fraction of open cells at percolation (line: 0.593; triangle: mean)
342 of 576
24 × 24
Heuristics in use
Open fraction pp0.594
Pointers per opening (with query)3.55
Experiments100
Mean threshold0.590 ± 0.004
Known value of pcp_c≈ 0.593
The grid percolates with 342 open cells (fraction 0.594). Orange cells form the cluster connecting top to bottom. With rank and compression, each opening cost an average of 3.55 pointers.
The grid starts at the moment it percolates: orange cells form the cluster connecting ceiling to floor. Drag ‘Open cells’ backward to see the blue ceiling-connected cluster grow. Click ‘+100 experiments’ several times: the histogram fills around 0.593, the mean's standard error decreases and the mean triangle falls almost on the line. Histogram width depends on size, not experiment count: larger grids have a sharper transition and narrower histogram. Cost is below: change heuristics and observe that without any, cost per opening grows with grid size; with rank alone it rises slowly and with compression it stays around 3 or 4 pointers (including the percolation query). Increase size to 40×4040 \times 40 and compare.

Tarjan’s offline LCA

The lowest common ancestor of two tree nodes (LCA) has an online solution using the RMQ reduction in the range-query lesson. If queries are known beforehand, there is an offline union-find solution (Tarjan, 1979): traverse the tree depth-first and when node vv finishes (its whole subtree has been traversed), first answer its queries and then merge its set with its parent’s, marking that parent as ancestro of the resulting set. For query (u,v)(u, v), when vv finishes and uu has already finished, LCA is the ancestro of uu‘s set at that moment (if uu is a descendant of vv, that ancestor is vv itself; order therefore matters). The invariant is that each set contains an open node (on the traversal stack) and completed nodes whose deepest open ancestor is it, and its ancestro is that open node; if uu is finished, the LCA of uu and the node being finished is precisely uu‘s deepest open ancestor. You will implement it in the coding exercise.

Offline connectivity with deletions

Union-find cannot delete: a tree cannot be “split” without knowing who hung under whom. But if deletions are known beforehand, time can be reversed.

For deletion-only sequences, start from the final graph (edges never deleted) and process deletions in reverse order: undoing deletion of edge ee inserts it, and union-find supports insertions. If query answers are saved in a list, read them backwards. Mixed insertions and deletions with arbitrary lifetimes are solved using a segment tree over time and union-find with rollback: union by size without compression, storing which root hung under which on a stack so it can be reverted. Without compression cost per operation is Θ(log⁡n)\Theta(\log n), and the technique gives O(qlog⁡qlog⁡n)\bigO(q \log q \log n) for qq updates. Compression cannot be combined with rollback cheaply: it rewrites many pointers, each of which would need logging.

[ ]Offline connectivity with deletions versus networkxBrowser
import random
import time
import networkx as nx

def componentes_tras_borrados(n, aristas, borrados):
    """Borrados conocidos de antemano: se procesan en orden inverso, que convierte el borrado en inserción.
    Devuelve la lista c, con c[i] = número de componentes tras borrar las i primeras aristas de `borrados`."""
    quitadas = set(borrados)
    d = DSU(n)
    comp = n
    for e in aristas:
        if e not in quitadas:               # el grafo final: lo que nunca se borra
            comp -= d.unir(*e)
    respuesta = [0] * (len(borrados) + 1)
    respuesta[len(borrados)] = comp
    for i in range(len(borrados) - 1, -1, -1):
        comp -= d.unir(*borrados[i])        # deshacer el borrado i es insertar esa arista
        respuesta[i] = comp
    return respuesta

def con_networkx(n, aristas, borrados):
    """Referencia: recalcular las componentes desde cero tras cada borrado."""
    g = nx.Graph()
    g.add_nodes_from(range(n))
    g.add_edges_from(aristas)
    res = [nx.number_connected_components(g)]
    for e in borrados:
        g.remove_edge(*e)
        res.append(nx.number_connected_components(g))
    return res

rng = random.Random(11)
n, m, k = 600, 720, 300
todas = set()
while len(todas) < m:
    a, b = rng.sample(range(n), 2)
    todas.add((min(a, b), max(a, b)))
aristas = sorted(todas)
borrados = rng.sample(aristas, k)           # orden de borrado

t0 = time.perf_counter()
rapida = componentes_tras_borrados(n, aristas, borrados)
t1 = time.perf_counter()
lenta = con_networkx(n, aristas, borrados)
t2 = time.perf_counter()
print(f"mismas respuestas: {rapida == lenta}")
print(f"componentes: al empezar {rapida[0]}, tras borrar {k} aristas {rapida[-1]}")
print(f"tiempo: union-find offline {1000 * (t1 - t0):.1f} ms, recalcular con networkx {1000 * (t2 - t1):.0f} ms")

This lab reuses the DSU class from the preceding cell. Both answer lists agree and the reverse method makes one union pass versus kk complete recomputations: recomputation time grows as Θ(k(n+m))\Theta(k(n + m)) and reverse-method time as O((n+m) α(n))\bigO((n + m)\,\alpha(n)).

Can it be done online? With deletions arriving without warning, union-find is insufficient. Holm, de Lichtenberg and Thorup (2001) solve it with amortized O(log⁡2n)\bigO(\log^2 n) per update using a hierarchy of spanning forests, and Pătraşcu and Demaine (2006) proved Ω(log⁡n)\Omega(\log n) unavoidable in the cell-probe model. This is the difference between a “nearly linear” problem and one with a logarithmic barrier.

With libraries

For a static graph union-find is rarely necessary: SciPy supplies scipy.sparse.csgraph.connected_components (graph traversal in C, linear time when the graph is already fully in memory) and scipy.cluster.hierarchy.linkage (single linkage is the minimum spanning tree). Ready-made structures also exist for the incremental version: scipy.cluster.hierarchy.DisjointSet (union by size and path halving) and networkx.utils.UnionFind (union by size and iterative full compression), both supporting arbitrary hashable elements, not just integers. The lab checks equivalence between Kruskal with union-find and single linkage, and between cutting the dendrogram and stopping Kruskal.

[ ]Kruskal with union-find versus SciPy single linkageBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components
from scipy.spatial.distance import pdist

rng = np.random.default_rng(3)
pts = np.vstack([rng.normal(c, 0.4, size=(40, 2)) for c in ([0, 0], [4, 0], [2, 3.5])])
n = len(pts)
d = pdist(pts)                                    # distancias en el orden de scipy: (0,1), (0,2), ..., (n-2, n-1)
i, j = np.triu_indices(n, k=1)
orden = np.argsort(d, kind="stable")

# Kruskal: recorrer las aristas por peso creciente y unir si no cierran un ciclo (con la clase DSU de arriba)
dsu, alturas, fusiones = DSU(n), [], 0
for e in orden:
    if dsu.unir(int(i[e]), int(j[e])):
        alturas.append(d[e])
        fusiones += 1
        if fusiones == n - 1:
            break

Z = linkage(pts, method="single")                 # el enlace simple es el árbol generador mínimo
print("alturas de fusión de Kruskal = alturas de linkage(single):", np.allclose(alturas, Z[:, 2]))

# cortar el dendrograma a la altura h equivale a parar Kruskal antes de las aristas de peso > h
h = 1.0
dsu2 = DSU(n)
for e in orden:
    if d[e] > h:
        break
    dsu2.unir(int(i[e]), int(j[e]))
mias = len({dsu2.buscar(x) for x in range(n)})
etiquetas = fcluster(Z, t=h, criterion="distance")
print(f"cortando a h = {h}: {mias} clusters con union-find, {len(set(etiquetas))} con fcluster")

# componentes conexas de un grafo disperso con la rutina de scipy (un recorrido del grafo en C)
mask = d <= h
G = coo_matrix((np.ones(mask.sum()), (i[mask], j[mask])), shape=(n, n))
k, lab = connected_components(G, directed=False)
print("scipy.sparse.csgraph.connected_components:", k, "componentes")

# la estructura incremental ya hecha de scipy: DisjointSet (unión por tamaño y reducción a la mitad)
from scipy.cluster.hierarchy import DisjointSet
ds = DisjointSet(range(n))
for e in orden:
    if d[e] > h:
        break
    ds.merge(int(i[e]), int(j[e]))
print("scipy.cluster.hierarchy.DisjointSet:", ds.n_subsets, "conjuntos")

Three practical ideas. First, single linkage is Kruskal: dendrogram merge heights are minimum-spanning-tree edge weights in increasing order, and cutting at height hh means stopping on reaching edges heavier than hh. Second, static graph components come from connected_components without union-find; union-find’s advantage is incremental updating. Third, for that incremental update DisjointSet agrees with the custom class but adds Python-dictionary overhead per operation; in a critical loop over integers 0,…,n−10, \dots, n-1, the well-tested twenty-line list-based version remains the natural choice, and is the only one that can be instrumented or modified (rollback, ancestors, weights).

Common mistakes

Exercises

ProofRank, descendants and logarithmic height
Prove: With union by rank (without path compression) starting from nn isolated nodes of rank 00, every node of rank rr has at least 2r2^r descendants (including itself). Consequently every tree's height is at most log⁡2n\log_2 n.
0
Let tam(x)\mathrm{tam}(x) be the number of descendants of xx (including xx). Use induction on the number of links. Initially all nodes have tam=1=20\mathrm{tam} = 1 = 2^0.

Step 1 of 4. Which nodes can change rank or size when linking root bb under root aa (with rango(b)≤rango(a)\mathrm{rango}(b) \le \mathrm{rango}(a))?

ProofCompression alone: Θ(n log n) cost
Prove: Without union by rank (linking always puts the first argument's root below the second's) and with full compression, there are sequences of m=Θ(n)m = \Theta(n) operations costing Θ(mlog⁡m)\Theta(m \log m) pointers.
0
Let B0B_0 be one node and BkB_k be the tree with a root whose children are roots of B0,B1,…,Bk−1B_0, B_1, \dots, B_{k-1}. It has 2k2^k nodes and depth kk. Build BkB_k by linking one Bk−1B_{k-1} root below another. With 2k2^k more nodes, perform 2k2^k rounds of ‘put a new root above the current one and search from the deepest leaf’.

Step 1 of 4. After building BkB_k and placing a new root xx above the root ρ\rho of BkB_k, how many pointers does a search from the deepest leaf follow?

NumericIterated logarithm of a tower
Calculate log⁡∗(265536)\log^*(2^{65536}), the number of times log⁡2\log_2 must be applied to 2655362^{65536} to reach a value ≤1\le 1.
Numericα for the universe's atom count
With α(n)=min⁡{k:Ak(1)≥n}\alpha(n) = \min\{k : A_k(1) \ge n\}, where A0(j)=j+1A_0(j) = j + 1 and Ak(j)=Ak−1(j+1)(j)A_k(j) = A_{k-1}^{(j+1)}(j), calculate α(1080)\alpha(10^{80}).
NumericChain and compression without rank
Given n=1000n = 1000 elements, perform union(0,1), union(1,2), ..., union(998,999) with naive linking (the first argument's root hangs below the second's), without union by rank and with full compression. Then perform 1010 find(0) searches. Counting one pointer per edge followed by find (including inside union), how many pointers are followed in total?
NumericRank blocks for n = 2^20
With rank blocks {0,1}\{0, 1\}, {2}\{2\}, {3,4}\{3, 4\}, {5,…,16}\{5, \dots, 16\}, {17,…,65536}\{17, \dots, 65536\}, ..., how many blocks (counting {0,1}\{0, 1\}) can a union-by-rank forest of n=220n = 2^{20} elements use?
QuizWhen does union-find work?
In which problems does union-find solve the task in nearly linear cost in the number of operations?

More than one answer may be correct.

QuizWhat fails in this union?
A colleague writes def union(x, y): padre[x] = y (without calling find first) and uses path compression in find. What happens with union(3, 5), union(3, 7), find(5) == find(7)?
CodeTarjan offline LCA
Implement lca_offline(n, padre, consultas): it receives the tree as array padre (padre[raiz] = -1; root can have any label) and a list of pairs (u, v), and returns each pair’s lowest common ancestor in the same order. Use Tarjan’s algorithm: an iterative depth-first traversal (tests include a 20000-node path) and union-find, merging each node with its parent when it finishes. A node counts as its own ancestor: lca(v, v) = v.
def lca_offline(n, padre, consultas):
  """LCA de cada par de la lista consultas con el algoritmo offline de Tarjan.
  padre[v] es el padre de v y padre[raiz] = -1. Devuelve la lista de ancestros comunes, en el orden de las consultas."""
  return []   # tu código
Shift+Enter to run

Summary

Key idea
A partition that only merges is stored as a pointer forest; linking by rank gives logarithmic-height trees, path compression shortens traversed paths, and together they cost amortized O(α(n))\bigO(\alpha(n)), optimal and practically constant but not a constant; the structure does not admit deletions.
  • Representation. An array padre; find climbs to the root, union links roots. Weighted-union lists already give O(m+nlog⁡n)\bigO(m + n \log n) (each element is relabeled at most log⁡2n\log_2 n times).
  • Union by rank or size: a node of rank rr has ≥2r\ge 2^r descendants and height is ≤log⁡2n\le \log_2 n. Path compression (full, splitting or halving): alone it gives Θ(mlog⁡1+m/nn)\Theta(m \log_{1+m/n} n), and binomial sequences force log⁡n\log n per round.
  • Both heuristics: O(mlog⁡∗n)\bigO(m \log^* n) by rank blocks (A, B and C charges), and O(m α(n))\bigO(m\,\alpha(n)) by Tarjan’s potential, with α(n)=min⁡{k:Ak(1)≥n}\alpha(n) = \min\{k : A_k(1) \ge n\} and α(n)≤4\alpha(n) \le 4 up to a tower of 2048 twos. The bound is optimal (Tarjan 1979, Fredman and Saks 1989) and is recovered with Seidel and Sharir’s top-down analysis.
  • Applications: Kruskal, percolation (virtual ceiling and floor nodes), image labeling, Tarjan’s offline LCA, offline connectivity with reversed deletions, rollback with union by size without compression.
  • Limits: no individual operation is constant, online deletion requires another structure (Holm, de Lichtenberg and Thorup, amortized O(log⁡2n)\bigO(\log^2 n)), and directed cycles are not a weak-connectivity problem.

Beyond this lesson, the idea of canonicalizing representatives with a tree that flattens as used reappears in unification, SMT solvers’ congruence closure, and single-linkage clustering in the clustering lesson. Analytically, this structure is the best example of a potential that measures nothing physical about state: it is accounting designed for the proof, with Ackermann staircase levels the program never computes. It is an extreme case of asymptotic notation: α(n)→∞\alpha(n) \to \infty, but no writable nn makes it exceed 4.