How union-find almost flattens a disjoint-set forest

Short answer: Union-find maintains a partition of elements under union and under “are these two in the same set.” Each set is a tree of parent pointers. Union by rank attaches the shorter tree under the taller one, and path compression points every node on a lookup path at the root. Together, m operations on n elements cost O(m α(n)) time, where α is the inverse Ackermann function and is at most 4 for every practical n. Either optimization alone is only logarithmic.


What the problem actually asks

Kruskal’s algorithm asks, over and over, whether two endpoints already lie in the same grown component, and if they do not, it merges those components. A linear scan of labels would make that test the slow part of the sort. A parent pointer turns each set into a tree whose root is the set’s name. The merge is a parent assignment. The test is two root lookups.

Without a balancing rule the tree can become a chain and each lookup is Θ(n). The two classical repairs are different: one limits height when trees are linked, and the other flattens a path the next time it is walked.


What the algorithm guarantees

Union by rank gives trees of height O(log n) and a cost of O(log n) per operation. Path compression alone, with a naive link, also reaches O(log n) amortized in the usual analysis of compression without rank, and the combination is the inverse-Ackermann bound. The bound is amortized. One unlucky operation can still walk a long path, after which that path is flat.

Union by size, which hangs the smaller tree under the larger, has the same logarithmic height bound as rank. Rank is an upper bound on height and does not have to be maintained as an exact size. Path compression must not be mixed with a height field that is treated as exact, because compression changes heights and rank does not claim to track them afterward. The structure does not support undo, split, or “list the members” in the same bound. Those are different data structures.


The working steps

  1. Set parent[x] = x and rank[x] = 0 for each element.
  2. Find(x) returns parent[x] if x is a root. Otherwise it sets parent[x] = Find(parent[x]) and returns that root. That assignment is path compression.
  3. Same(a, b) compares Find(a) with Find(b).
  4. Union(a, b) finds both roots. If they differ, the root of smaller rank becomes a child of the root of larger rank. Equal ranks pick either root as parent and increment that parent’s rank.
  5. A successful union returns the new root if the caller is Kruskal and only needs the merge, not the element list.

The inverse-Ackermann bound includes both rank and compression. Quoting it for a parent pointer with neither optimization describes a chain. The structure answers connectivity in a growing partition. It does not store the minimum edge between components unless an extra value is kept at the root, and it does not answer dynamic connectivity after deletions.


Approaches that look simpler and fail

Approach Why it fails when one of the two optimizations is omitted from the bound
Quote O(m α(n)) for union by rank without compression The cost per operation is then Θ(log n) in the worst case. α appears only with both improvements.
Compress paths and also decrement ranks as if they were heights Rank is not exact height after compression. Changing it breaks the link rule that keeps the potential in the proof.
Attach an arbitrary root under the other with no rank or size Adversarial unions build a chain. Each find walks Θ(n) parents.
Use the structure to delete an edge from a spanning tree Union has no inverse. Dynamic connectivity with deletions needs a different algorithm, such as a link-cut tree for forests.

The classical client is Kruskal. Any other incremental connectivity problem on an undirected graph, including connected components of a static graph if one prefers this over DFS, uses the same two operations. Offline lowest common ancestors via Tarjan also union subtrees during a depth-first search.


A working example

The Bash script and the Python script union by rank and compress paths. After linking 0-1, 2-3, and 1-2, index 0 and index 3 are one set and index 4 is another. Both print 1 0.

for ((i=0; i<5; i++)); do parent[i]=$i; rank[i]=0; done
find() {
  local x=$1
  while (( parent[x] != x )); do
    parent[x]=${parent[parent[x]]}
    x=${parent[x]}
  done
  echo "$x"
}
union() {
  local a b
  a=$(find "$1"); b=$(find "$2")
  if (( a == b )); then return; fi
  if (( rank[a] < rank[b] )); then local t=$a; a=$b; b=$t; fi
  parent[b]=$a
  if (( rank[a] == rank[b] )); then rank[a]=$((rank[a]+1)); fi
}
union 0 1
union 2 3
union 1 2
fa=$(find 0); fb=$(find 3); fc=$(find 4)
if (( fa == fb )); then s1=1; else s1=0; fi
if (( fa == fc )); then s2=1; else s2=0; fi
echo "$s1 $s2"
parent = list(range(5))
rank = [0] * 5

def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x

def union(a, b):
    a, b = find(a), find(b)
    if a == b:
        return
    if rank[a] < rank[b]:
        a, b = b, a
    parent[b] = a
    if rank[a] == rank[b]:
        rank[a] += 1

union(0, 1)
union(2, 3)
union(1, 2)
print(int(find(0) == find(3)), int(find(0) == find(4)))

Where it is used

Union-find is the disjoint-set structure inside Kruskal’s algorithm and inside connected-component labeling of an image. Network connectivity and equivalence classes in a compiler use the same parent array. A breadth-first search labels one component; the forest labels all of them.


When you can drop this algorithm

Drop union-find when the graph is static and a DFS or BFS component labeling is simpler. Keep it when edges arrive in a stream, when unions are interleaved with queries, or when Kruskal needs the cycle test. Implement both union by rank and path compression if the inverse-Ackermann bound is the one you are relying on.


Why this stays published

We publish this so a search for union-find returns the pair of optimizations that the inverse-Ackermann bound actually requires. Union-find with union by rank and path compression answers m connectivity operations on n elements in O(m α(n)) time, and either optimization by itself is only logarithmic.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *