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 operations on elements takes time, where is the inverse of a function that grows so explosively that for every up to a number with more than digits. This lesson defines , states the theorem, proves the key facts about ranks, and proves two weaker but instructive bounds: for union by rank alone, and for both heuristics together.
A function that grows absurdly fast, and its inverse
Define functions for on the positive integers by iteration:
where means applied times. Each level iterates the previous one:
- (add one, times);
- , exponential;
- ;
- , which is far larger than ; in fact it is beyond any tower of exponentials you could write down.
The inverse Ackermann function is
so for respectively, and for all , which covers any conceivable input. The program evaluates the small values directly.
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 in the last column, the number of times must be applied to get down to at most 1 (Factorials, Stirling and the Iterated Logarithm), also grows unimaginably slowly ( for ), but grows more slowly still.
The theorem
Theorem (Tarjan, 1975). A sequence of MAKE-SET, UNION and FIND-SET operations, of which are MAKE-SETs, on a disjoint-set forest with union by rank and path compression takes time in the worst case.
The bound is tight: Tarjan showed that a broad class of pointer-based algorithms needs , 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 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):
- Ranks increase towards the root. For every non-root , . A node only gets a parent when it is linked under a root of larger rank, or of equal rank that then grows. Afterwards is not a root, so its rank never changes, while its parent's rank can only grow. Compression replaces 's parent by an ancestor, whose rank is even larger.
- A root of rank has at least nodes in its tree. By induction on the links: a root first gets rank when two roots of rank are linked, each with at least nodes. Compression moves nodes within a tree, never out of it.
- There are at most nodes of rank . When a node first reaches rank it is a root, and by fact 2 its tree has at least nodes; give each of them the label . No node is labelled twice for the same rank. From the moment is labelled, the root of 's tree has rank at least (it is or an ancestor of , fact 1). Another node could only label by reaching rank as the root of 's tree, but that root already has rank at least , and ranks never decrease, so it reached rank before was in its tree. The groups of at least labelled nodes are therefore disjoint, and there are at most of them. In particular every rank is at most .
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.
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:
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 steps. Each union is two finds plus . So operations take time. The balanced construction in the previous lesson shows this is tight without compression.
The bound with both heuristics
Proof (Hopcroft and Ullman's argument, in outline)
Group the ranks into blocks. Let and , a tower of twos (). Block contains the ranks with , and block 0 the ranks 0 and 1. Ranks are at most , so only blocks are used.
Count the pointer steps of each FIND-SET, one step for each node on the path whose parent is followed. Charge the step:
- to the find, if 's parent is the root, or if and its parent have ranks in different blocks. Ranks increase along the path (fact 1), so the block changes at most times on one path: each find is charged .
- to the node otherwise. Then 's parent is not the root, so compression gives a new parent: the root, whose rank is strictly larger than the rank of 's old parent (fact 1 along the path). So every charge to increases the rank of 's parent. The rank of itself is fixed (it is not a root), and once the parent's rank leaves 's block, is never charged again. If 's rank is in block , it is charged at most times.
By fact 3, the number of nodes with ranks in block is at most
so all nodes of block together are charged fewer than times. Over blocks, the nodes receive charges in total, and the finds . Since , the whole sequence takes time.
The same idea with a much finer measure of "how far the parent's rank is ahead", defined by the functions, gives Tarjan's .
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 .
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 ?
- 7
- 15
- 2047
For which is ?
- only
- for all , a number far beyond , so for every practical input
- only for
- for no
With union by rank, why are there at most nodes of rank ?
- Because ranks are random
- Because each rank- node had a tree of at least nodes when it reached rank , and these groups of nodes are disjoint for different rank- nodes
- Because path compression lowers ranks
- Because there are at most unions
Without path compression but with union by rank, what is the worst-case cost of one FIND-SET?