TExcelTAD

Why Union-Find Is Almost Linear

With union by rank and path compression, the experiments of the previous lesson found about one pointer step per operation. The theory says almost exactly that: a sequence of mm operations on nn elements takes O(m α(n))O(m \, \alpha(n)) time, where α\alpha is the inverse of a function that grows so explosively that α(n)≤4\alpha(n) \le 4 for every nn up to a number with more than 108010^{80} digits. This lesson defines α\alpha, states the theorem, proves the key facts about ranks, and proves two weaker but instructive bounds: O(mlg⁡n)O(m \lg n) for union by rank alone, and O(mlg⁡∗n)O(m \lg^* n) for both heuristics together.

A function that grows absurdly fast, and its inverse

Define functions AkA_k for k≥0k \ge 0 on the positive integers by iteration:

A0(j)=j+1,Ak(j)=Ak−1(j+1)(j)for k≥1A_0(j) = j + 1, \qquad A_k(j) = A_{k-1}^{(j+1)}(j) \quad \text{for } k \ge 1

where f(i)f^{(i)} means ff applied ii times. Each level iterates the previous one:

  • A1(j)=2j+1A_1(j) = 2j + 1 (add one, j+1j + 1 times);
  • A2(j)=2j+1(j+1)−1A_2(j) = 2^{j+1}(j + 1) - 1, exponential;
  • A3(1)=A2(A2(1))=A2(7)=28⋅8−1=2047A_3(1) = A_2(A_2(1)) = A_2(7) = 2^8 \cdot 8 - 1 = 2047;
  • A4(1)=A3(A3(1))=A3(2047)A_4(1) = A_3(A_3(1)) = A_3(2047), which is far larger than A2(2047)=22048⋅2048−1>10616A_2(2047) = 2^{2048} \cdot 2048 - 1 > 10^{616}; in fact it is beyond any tower of exponentials you could write down.

The inverse Ackermann function is

α(n)=min⁡{k:Ak(1)≥n}\alpha(n) = \min \{ k : A_k(1) \ge n \}

so α(n)=0,1,2,3\alpha(n) = 0, 1, 2, 3 for n≤2,3,7,2047n \le 2, 3, 7, 2047 respectively, and α(n)≤4\alpha(n) \le 4 for all n≤A4(1)n \le A_4(1), which covers any conceivable input. The program evaluates the small values directly.

python · try it yourself
import math

def A(k, j):
    if k == 0:
        return j + 1
    for _ in range(j + 1):          # A_k(j) = A_{k-1} applied j + 1 times to j
        j = A(k - 1, j)
    return j

print("A_1(j) for j = 1..5:", [A(1, j) for j in range(1, 6)])
print("A_2(j) for j = 1..5:", [A(2, j) for j in range(1, 6)], "= 2^(j+1)(j+1) - 1:", [2 ** (j + 1) * (j + 1) - 1 for j in range(1, 6)])
print("A_k(1) for k = 0..3:", [A(k, 1) for k in range(4)])

def alpha(n):
    k = 0
    while (A(k, 1) if k < 4 else math.inf) < n:      # A_4(1) is far too large to compute
        k += 1
    return k

def lg_star(n):
    s = 0
    while n > 1:
        n, s = math.log2(n), s + 1
    return s

for n in [2, 3, 7, 8, 2047, 2048, 10 ** 6, 10 ** 80]:
    shown = f"{n:.0e}" if n > 10 ** 7 else str(n)
    print(f"n = {shown:<8} alpha(n) = {alpha(n)}   lg* n = {lg_star(n)}   lg n = {math.log2(n):.1f}")
A_1(j) for j = 1..5: [3, 5, 7, 9, 11]
A_2(j) for j = 1..5: [7, 23, 63, 159, 383] = 2^(j+1)(j+1) - 1: [7, 23, 63, 159, 383]
A_k(1) for k = 0..3: [2, 3, 7, 2047]
n = 2        alpha(n) = 0   lg* n = 1   lg n = 1.0
n = 3        alpha(n) = 1   lg* n = 2   lg n = 1.6
n = 7        alpha(n) = 2   lg* n = 3   lg n = 2.8
n = 8        alpha(n) = 3   lg* n = 3   lg n = 3.0
n = 2047     alpha(n) = 3   lg* n = 4   lg n = 11.0
n = 2048     alpha(n) = 4   lg* n = 4   lg n = 11.0
n = 1000000  alpha(n) = 4   lg* n = 5   lg n = 19.9
n = 1e+80    alpha(n) = 4   lg* n = 5   lg n = 265.8

The iterated logarithm lg⁡∗n\lg^* n in the last column, the number of times lg⁡\lg must be applied to get down to at most 1 (Factorials, Stirling and the Iterated Logarithm), also grows unimaginably slowly (lg⁡∗n≤5\lg^* n \le 5 for n≤265536n \le 2^{65536}), but α\alpha grows more slowly still.

The theorem

Theorem (Tarjan, 1975). A sequence of mm MAKE-SET, UNION and FIND-SET operations, nn of which are MAKE-SETs, on a disjoint-set forest with union by rank and path compression takes O(m α(n))O(m \, \alpha(n)) time in the worst case.

The bound is tight: Tarjan showed that a broad class of pointer-based algorithms needs Ω(m α(n))\Omega(m \, \alpha(n)), and Fredman and Saks proved the same lower bound in the cell-probe model, so no disjoint-set structure can be linear in general. The proof of the upper bound uses a potential function built from AkA_k and is several pages long. The rest of this lesson proves the facts it rests on and the easier bounds.

Three facts about ranks

With union by rank (and compression or not):

  1. Ranks increase towards the root. For every non-root xx, x.rank<x.p.rankx.\textit{rank} < x.p.\textit{rank}. A node only gets a parent when it is linked under a root of larger rank, or of equal rank that then grows. Afterwards xx is not a root, so its rank never changes, while its parent's rank can only grow. Compression replaces xx's parent by an ancestor, whose rank is even larger.
  2. A root of rank rr has at least 2r2^r nodes in its tree. By induction on the links: a root first gets rank rr when two roots of rank r−1r - 1 are linked, each with at least 2r−12^{r-1} nodes. Compression moves nodes within a tree, never out of it.
  3. There are at most n/2rn / 2^r nodes of rank rr. When a node xx first reaches rank rr it is a root, and by fact 2 its tree has at least 2r2^r nodes; give each of them the label xx. No node yy is labelled twice for the same rank. From the moment yy is labelled, the root of yy's tree has rank at least rr (it is xx or an ancestor of xx, fact 1). Another node could only label yy by reaching rank rr as the root of yy's tree, but that root already has rank at least rr, and ranks never decrease, so it reached rank rr before yy was in its tree. The groups of at least 2r2^r labelled nodes are therefore disjoint, and there are at most n/2rn / 2^r of them. In particular every rank is at most ⌊lg⁡n⌋\lfloor \lg n \rfloor.

The program runs random sequences with both heuristics and checks all three facts after every operation, together with the stronger fact that the height (without compression, in a separate run) never exceeds the rank.

python · try it yourself
import random
from collections import Counter

def run(n, ops, compress):
    p, rank, size = list(range(n)), [0] * n, [1] * n
    def find(x):
        root = x
        while p[root] != root: root = p[root]
        while compress and p[x] != root: p[x], x = root, p[x]
        return root
    def depth(x):
        d = 0
        while p[x] != x: x, d = p[x], d + 1
        return d
    for x, y in ops:
        a, b = find(x), find(y)
        if a != b:
            if rank[a] < rank[b]: a, b = b, a
            p[b] = a; size[a] += size[b]
            if rank[a] == rank[b]: rank[a] += 1
        assert all(rank[v] < rank[p[v]] for v in range(n) if p[v] != v)              # fact 1
        assert all(size[r] >= 2 ** rank[r] for r in range(n) if p[r] == r)           # fact 2
        counts = Counter(rank)
        assert all(c <= n / 2 ** r for r, c in counts.items())                       # fact 3
        if not compress:
            assert all(depth(v) <= rank[find(v)] for v in (x, y))                    # height <= rank
    return max(rank)

rng = random.Random(9)
n = 256
for compress in [True, False]:
    ops = [(rng.randrange(n), rng.randrange(n)) for _ in range(600)]
    print(f"compression {'on ' if compress else 'off'}: facts 1-3 hold after all 600 unions; largest rank {run(n, ops, compress)} (lg n = 8)")
compression on : facts 1-3 hold after all 600 unions; largest rank 4 (lg n = 8)
compression off: facts 1-3 hold after all 600 unions; largest rank 4 (lg n = 8)

The easy bound: O(mlg⁡n)O(m \lg n)

With union by rank alone, a tree's height equals its root's rank (both grow only at links between equal ranks), so by fact 3 every find takes O(lg⁡n)O(\lg n) steps. Each union is two finds plus O(1)O(1). So mm operations take O(mlg⁡n)O(m \lg n) time. The balanced construction in the previous lesson shows this is tight without compression.

The O(mlg⁡∗n)O(m \lg^* n) bound with both heuristics

Proof (Hopcroft and Ullman's argument, in outline)

Group the ranks into blocks. Let T(0)=1T(0) = 1 and T(g)=2T(g−1)T(g) = 2^{T(g-1)}, a tower of gg twos (T=1,2,4,16,65536,…T = 1, 2, 4, 16, 65536, \ldots). Block g≥1g \ge 1 contains the ranks rr with T(g−1)<r≤T(g)T(g-1) < r \le T(g), and block 0 the ranks 0 and 1. Ranks are at most lg⁡n\lg n, so only O(lg⁡∗n)O(\lg^* n) blocks are used.

Count the pointer steps of each FIND-SET, one step for each node xx on the path whose parent is followed. Charge the step:

  • to the find, if xx's parent is the root, or if xx and its parent have ranks in different blocks. Ranks increase along the path (fact 1), so the block changes at most O(lg⁡∗n)O(\lg^* n) times on one path: each find is charged O(lg⁡∗n)O(\lg^* n).
  • to the node xx otherwise. Then xx's parent is not the root, so compression gives xx a new parent: the root, whose rank is strictly larger than the rank of xx's old parent (fact 1 along the path). So every charge to xx increases the rank of xx's parent. The rank of xx itself is fixed (it is not a root), and once the parent's rank leaves xx's block, xx is never charged again. If xx's rank is in block gg, it is charged at most T(g)−T(g−1)<T(g)T(g) - T(g-1) < T(g) times.

By fact 3, the number of nodes with ranks in block gg is at most

∑r>T(g−1)n2r≤n2T(g−1)=nT(g)\sum_{r > T(g-1)} \frac{n}{2^r} \le \frac{n}{2^{T(g-1)}} = \frac{n}{T(g)}

so all nodes of block gg together are charged fewer than T(g)⋅n/T(g)=nT(g) \cdot n / T(g) = n times. Over O(lg⁡∗n)O(\lg^* n) blocks, the nodes receive O(nlg⁡∗n)O(n \lg^* n) charges in total, and the finds O(mlg⁡∗n)O(m \lg^* n). Since n≤mn \le m, the whole sequence takes O(mlg⁡∗n)O(m \lg^* n) time.

The same idea with a much finer measure of "how far the parent's rank is ahead", defined by the AkA_k functions, gives Tarjan's O(m α(n))O(m \, \alpha(n)).

The theory in numbers

Finally, the program counts parent steps per operation for both heuristics on larger random inputs and on a sequence of balanced unions followed by finds on every element in random order. The cost per operation stays near 1, for every nn.

python · try it yourself
import random

def steps_per_op(n, ops):
    p, rank, steps = list(range(n)), [0] * n, 0
    def find(x):
        nonlocal steps
        root = x
        while p[root] != root:
            root = p[root]; steps += 1
        while p[x] != root:
            p[x], x = root, p[x]
        return root
    for op, x, y in ops:
        if op == "f":
            find(x); continue
        a, b = find(x), find(y)
        if a != b:
            if rank[a] < rank[b]: a, b = b, a
            p[b] = a
            if rank[a] == rank[b]: rank[a] += 1
    return steps / len(ops)

rng = random.Random(4)
print(f"{'n':>7} {'random mix':>11} {'balanced + all finds':>21}")
for n in [1 << 10, 1 << 13, 1 << 16]:
    rand = [("u" if rng.random() < 0.5 else "f", rng.randrange(n), rng.randrange(n)) for _ in range(2 * n)]
    bal, step = [], 1
    while step < n:
        bal += [("u", i, i + step) for i in range(0, n, 2 * step)]
        step *= 2
    order = list(range(n)); rng.shuffle(order)
    bal += [("f", v, 0) for v in order]
    print(f"{n:>7} {steps_per_op(n, rand):>11.3f} {steps_per_op(n, bal):>21.3f}")
      n  random mix  balanced + all finds
   1024       0.925                 0.995
   8192       0.959                 0.999
  65536       0.966                 1.000

Test yourself

What is A3(1)A_3(1)?

  1. 7
  2. 15
  3. 2047
  4. 220472^{2047}

For which nn is α(n)≤4\alpha(n) \le 4?

  1. only n≤2047n \le 2047
  2. for all n≤A4(1)n \le A_4(1), a number far beyond 108010^{80}, so for every practical input
  3. only for n≤106n \le 10^6
  4. for no nn

With union by rank, why are there at most n/2rn/2^r nodes of rank rr?

  1. Because ranks are random
  2. Because each rank-rr node had a tree of at least 2r2^r nodes when it reached rank rr, and these groups of nodes are disjoint for different rank-rr nodes
  3. Because path compression lowers ranks
  4. Because there are at most lg⁡n\lg n unions

Without path compression but with union by rank, what is the worst-case cost of one FIND-SET?

  1. O(1)O(1)
  2. O(α(n))O(\alpha(n))
  3. O(lg⁡n)O(\lg n)
  4. O(n)O(n)