TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Forests: Union by Rank and Path Compression

Forests: Union by Rank and Path Compression

The fastest known disjoint-set structure is also one of the shortest pieces of code in this course. Each set is a rooted tree, and each element stores only a pointer to its parent: the parent array layout. The root of a tree is its set's representative and points to itself. FIND-SET walks up to the root; UNION makes one root point to the other. On its own that is no better than linked lists, since the trees can degenerate into long paths. Two heuristics, union by rank and path compression, make the trees so flat that a sequence of mm operations costs O(m α(n))O(m \, \alpha(n)), where α\alpha is a function that is at most 4 for any nn you will ever see.

The forest and the two heuristics

Without heuristics:

text
MAKE-SET(x):  x.p = x
FIND-SET(x):  while x != x.p: x = x.p;  return x
UNION(x, y):  FIND-SET(y).p = FIND-SET(x)        // the second root now points to the first

A sequence like UNION(x2,x1)(x_2, x_1), UNION(x3,x2)(x_3, x_2), … builds a path of length n−1n - 1, and FIND-SET on its bottom element walks all of it.

Union by rank. Each root carries a rank, an upper bound on the height of its tree; MAKE-SET sets it to 0. UNION links the root of smaller rank under the root of larger rank, so the taller tree's height does not grow. Only when the ranks are equal does the new root's rank go up by one. (Union by size, linking the smaller tree under the larger, works just as well.)

Path compression. FIND-SET(x)(x) walks from xx to the root anyway. On the way back it makes every node on the path point directly at the root. The next find for any of them takes one step. Ranks are not changed by compression, which is why a rank is only an upper bound on the height.

text
MAKE-SET(x)                    FIND-SET(x)                     UNION(x, y)
1  x.p = x                     1  if x != x.p                  1  LINK(FIND-SET(x), FIND-SET(y))
2  x.rank = 0                  2      x.p = FIND-SET(x.p)      
                               3  return x.p                   LINK(a, b)            // a, b are roots
                                                               1  if a == b: return
                                                               2  if a.rank < b.rank: swap a and b
                                                               3  b.p = a
                                                               4  if a.rank == b.rank: a.rank = a.rank + 1

FIND-SET is a two-pass method: the recursion goes up to find the root, and as it unwinds it sets each parent pointer to the root.

Watching it work

The Python version prints the same steps: the path followed by each find, the compressions, and each link with its rank update. Like the animation, LINK keeps the first argument's root on ties.

python · try it yourself
class DisjointSets:
    def __init__(self, names):
        self.p = {x: x for x in names}
        self.rank = {x: 0 for x in names}
    def find(self, x, why=""):
        path = [x]
        while self.p[path[-1]] != path[-1]:
            path.append(self.p[path[-1]])
        root = path[-1]
        print(f"{why}find({x}): {' -> '.join(path)}, root {root}")
        if len(path) > 2:
            for v in path[:-1]:
                self.p[v] = root                     # path compression
            print(f"  compress: {', '.join(path[:-2])} now point(s) at {root}")
        return root
    def union(self, x, y):
        a, b = self.find(x, f"union({x}, {y}): "), self.find(y, f"union({x}, {y}): ")
        if a == b:
            print(f"  {x} and {y} are already in the same set"); return
        if self.rank[a] < self.rank[b]:
            a, b = b, a
        self.p[b] = a
        bump = self.rank[a] == self.rank[b]
        if bump:
            self.rank[a] += 1
        print(f"  link {b} under {a}" + (f"; equal ranks, rank of {a} is now {self.rank[a]}" if bump else ""))

ds = DisjointSets("ABCDEFGH")
for op in ["union A B", "union C D", "union B D", "union E F", "union G H", "union F H", "union D H", "find H", "find C"]:
    name, *args = op.split()
    getattr(ds, name)(*args)
print("parents:", ds.p)
print("ranks of roots:", {x: r for x, r in ds.rank.items() if ds.p[x] == x})
union(A, B): find(A): A, root A
union(A, B): find(B): B, root B
  link B under A; equal ranks, rank of A is now 1
union(C, D): find(C): C, root C
union(C, D): find(D): D, root D
  link D under C; equal ranks, rank of C is now 1
union(B, D): find(B): B -> A, root A
union(B, D): find(D): D -> C, root C
  link C under A; equal ranks, rank of A is now 2
union(E, F): find(E): E, root E
union(E, F): find(F): F, root F
  link F under E; equal ranks, rank of E is now 1
union(G, H): find(G): G, root G
union(G, H): find(H): H, root H
  link H under G; equal ranks, rank of G is now 1
union(F, H): find(F): F -> E, root E
union(F, H): find(H): H -> G, root G
  link G under E; equal ranks, rank of E is now 2
union(D, H): find(D): D -> C -> A, root A
  compress: D now point(s) at A
union(D, H): find(H): H -> G -> E, root E
  compress: H now point(s) at E
  link E under A; equal ranks, rank of A is now 3
find(H): H -> E -> A, root A
  compress: H now point(s) at A
find(C): C -> A, root A
parents: {'A': 'A', 'B': 'A', 'C': 'A', 'D': 'A', 'E': 'A', 'F': 'E', 'G': 'E', 'H': 'A'}
ranks of roots: {'A': 3}

After seven unions all eight elements are in one tree of rank 3, and the finds at the end touch at most two edges. Without compression the last union would have left H at depth 3 below A.

In C++

The standard C++ implementation is two arrays and a few lines. FIND-SET here is iterative (one pass up, one pass to compress), which avoids deep recursion. The program builds a long chain without the heuristics and then with them, and measures the parent steps of 20,000 random finds on 20,000 elements in each.

cpp · try it yourself
#include <cstdio>
#include <numeric>
#include <random>
#include <utility>
#include <vector>

class DSU {
    std::vector<int> p_, rank_;
    bool heuristics_;
public:
    long steps = 0;                                       // parent pointers followed by finds
    DSU(int n, bool heuristics) : p_(n), rank_(n, 0), heuristics_(heuristics) { std::iota(p_.begin(), p_.end(), 0); }
    int find(int x) {
        int root = x;
        while (p_[root] != root) { root = p_[root]; ++steps; }
        if (heuristics_)
            while (p_[x] != root) { int next = p_[x]; p_[x] = root; x = next; }   // path compression
        return root;
    }
    bool unite(int x, int y) {
        int a = find(x), b = find(y);
        if (a == b) return false;
        if (heuristics_ && rank_[a] < rank_[b]) std::swap(a, b);                    // union by rank
        p_[b] = a;
        if (heuristics_ && rank_[a] == rank_[b]) ++rank_[a];
        return true;
    }
};

int main() {
    const int n = 20000;
    for (bool h : {false, true}) {
        DSU ds(n, h);
        for (int i = 1; i < n; ++i) ds.unite(i, i - 1);                  // the chain-building sequence
        long build = ds.steps;
        ds.steps = 0;
        std::mt19937 rng(5);
        for (int q = 0; q < 20000; ++q) ds.find(static_cast<int>(rng() % n));
        std::printf("%-15s steps while building %6ld, steps for 20000 random finds %10ld\n",
                    h ? "rank+compress:" : "no heuristics:", build, ds.steps);
    }
}
no heuristics:  steps while building      0, steps for 20000 random finds  198876319
rank+compress:  steps while building  19997, steps for 20000 random finds      19998

Without heuristics the chain sequence makes every UNION link the long path under a new singleton, and the random finds then walk about n/2n/2 steps each. With both heuristics the whole run costs about one step per operation.

How much each heuristic helps

The program runs one sequence of 10,000 random unions and finds on 2000 elements with each of the four combinations, and counts parent pointers followed. Then it uses a sequence designed against union by rank alone: it builds a tree of height lg⁡n\lg n (by uniting equal trees, round by round) and then finds the deepest node repeatedly.

python · try it yourself
import random

def run(n, ops, rank_on, compress_on):
    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
        if compress_on:
            while p[x] != root:
                p[x], x = root, p[x]
        return root
    for op, x, y in ops:
        if op == "find":
            find(x); continue
        a, b = find(x), find(y)
        if a == b: continue
        if rank_on and rank[a] < rank[b]: a, b = b, a
        p[b] = a
        if rank_on and rank[a] == rank[b]: rank[a] += 1
    return steps

n = 2000
rng = random.Random(77)
random_ops = [("union" if rng.random() < 0.5 else "find", rng.randrange(n), rng.randrange(n)) for _ in range(10000)]
k = 1 << 15                                        # a tree of height 15 built from equal halves
balanced = []
step = 1
while step < k:
    balanced += [("union", i, i + step) for i in range(0, k, 2 * step)]
    step *= 2
deep = [("find", k - 1, 0)] * 20000                # node k - 1 ends up deepest
print(f"{'heuristics':24} {'random ops':>12} {'balanced + deep finds':>22}")
for rank_on, compress_on, name in [(False, False, "none"), (True, False, "union by rank"),
                                   (False, True, "path compression"), (True, True, "both")]:
    a = run(n, random_ops, rank_on, compress_on)
    b = run(k, balanced + deep, rank_on, compress_on)
    print(f"{name:24} {a:>12,} {b:>22,}")
heuristics                 random ops  balanced + deep finds
none                        2,065,512                300,000
union by rank                  22,737                300,000
path compression               28,249                 20,014
both                           12,933                 20,014

On random operations the plain forest follows about a hundred times more pointers than with either heuristic, and the two together are best. The second sequence separates the heuristics. Uniting equal halves round by round builds the same tree of height 15 with or without union by rank, and without compression every one of the 20,000 finds on the deepest node walks all 15 levels. With path compression the first find flattens the path, and each later find takes one step.

Test yourself

UNION links a root of rank 2 and a root of rank 3. Which becomes the parent, and what is the new rank?

  1. the rank-2 root, rank 3
  2. the rank-3 root, rank 3
  3. the rank-3 root, rank 4
  4. either, rank 5

What does path compression change?

  1. the ranks of the nodes on the path
  2. the parent pointers of the nodes on the find path, which then point directly at the root
  3. the representative of the set
  4. the number of sets

With union by rank alone (no compression), what is the height of a tree of nn elements at most?

  1. O(1)O(1)
  2. ⌊lg⁡n⌋\lfloor \lg n \rfloor
  3. n\sqrt{n}
  4. n−1n - 1