13. Union-Find / Disjoint Sets

Track connected components in near-constant time

You have a million users on a social network and someone asks: "Are Alice and Bob in the same friend group?" Two computers on a network go down — are they on the same subnet? You're building a maze and need to know whether two cells are already connected.

All of these boil down to the same abstract problem: given a collection of elements, group them into disjoint sets (non-overlapping groups), and efficiently answer two questions — which group is this element in? and merge these two groups. The data structure that solves this elegantly is called Union-Find (also known as a Disjoint Set Union, or DSU).

The Problem

We need a data structure that supports three operations on a universe of elements:

Operation Description
MakeSet(x) Create a new set containing only element x
Find(x) Return the representative (identifier) of the set containing x
Union(x, y) Merge the sets containing x and y into one

Two elements are in the same set if and only if Find(x) == Find(y). The challenge is making both Find and Union fast.

Naive Approaches

Array-based (Quick Find)

Store an array id[] where id[x] is the set representative. Find is O(1) — just read the array. But Union is O(n): to merge two sets, you must scan the entire array and update every element in one set to point to the other's representative.

Linked-list-based

Each set is a linked list. Union is O(1) if you just append one list to another — but you need to update the representative pointer for every node in the appended list. Without a trick, Union is still O(n) in the worst case.

Neither approach gives us fast performance for both operations simultaneously. We need a smarter structure.

The Tree-Based Approach

The key idea: represent each set as a rooted tree. Every element points to a parent. The root of the tree is the set's representative — it points to itself.

A forest of disjoint sets

After MakeSet for elements 0..6, each is its own tree:

0 1 2 3 4 5 6 (each node is its own root — parent[i] = i)

After Union(1, 2) and Union(3, 4) and Union(4, 5):

0 1 3 6 | /
2 4 5

Two trees of size >1, plus singletons 0 and 6. Find(2) = 1, Find(5) = 3, Find(0) = 0

Find: Follow Parent Pointers

To find which set an element belongs to, simply walk up the parent pointers until you reach the root (an element whose parent is itself):

function Find(x):
    while parent[x] != x:
        x = parent[x]
    return x

In the worst case — a long, skinny chain — this takes O(n) time. That's no better than the naive approach. We'll fix this shortly.

Union: Link Two Roots

To merge the sets containing x and y, find their roots and make one root point to the other:

function Union(x, y):
    rootX = Find(x)
    rootY = Find(y)
    if rootX == rootY: return   // already in the same set
    parent[rootX] = rootY       // attach x's tree under y's root

This is O(1) after the Find calls — but naive Union can produce degenerate chains. Imagine unioning elements 0 → 1 → 2 → 3 → ... in order. You get a linked list, and Find becomes O(n). We need two optimizations.

Optimization 1: Union by Rank

The idea

Always attach the shorter tree under the taller one. This keeps trees balanced and limits their height to O(log n).

We maintain a rank[] array — an upper bound on the height of each node's subtree. When merging, the root with the smaller rank becomes a child of the root with the larger rank. If ranks are equal, pick either one and increment its rank.

Union by rank in action

Union(A, B) where rank[rootA] = 1, rank[rootB] = 2:

Before: After (attach shorter under taller):

rootA rootB rootB | / \ /|
a b c b c rootA | a

rank[rootB] stays 2 — the tree didn't get taller.

function Union(x, y):
    rootX = Find(x)
    rootY = Find(y)
    if rootX == rootY: return

    if rank[rootX] < rank[rootY]:
        parent[rootX] = rootY
    else if rank[rootX] > rank[rootY]:
        parent[rootY] = rootX
    else:
        parent[rootY] = rootX
        rank[rootX] += 1

With union by rank alone, Find is guaranteed O(log n). Good — but we can do even better.

Optimization 2: Path Compression

The idea

Every time you call Find, make every node along the path point directly to the root. Future queries on those nodes become O(1).

Path compression during Find(e)

Before Find(e):            After Find(e):

  a                    a
  |                   /|\
  b                  b c d
  |                    |
  c                    e
  |
  d
  |
  e

Every node on the path now points directly to root a.

function Find(x):
    if parent[x] != x:
        parent[x] = Find(parent[x])    // recursively compress
    return parent[x]

Path compression doesn't change the set structure — it just flattens the tree so future operations are faster. It's a form of amortized self-adjustment: you pay a little extra now to save a lot later.

Worked Example: Building Connected Components

Let's trace through a sequence of operations on elements {0, 1, 2, 3, 4, 5}, using both union by rank and path compression.

  1. MakeSet for all elements

    parent = [0,1,2,3,4,5], rank = [0,0,0,0,0,0]
    Six isolated nodes. Each is its own root.

  2. Union(0, 1)

    Roots: 0 and 1, both rank 0. Attach 1 under 0, increment rank[0].
    parent = [0,0,2,3,4,5], rank = [1,0,0,0,0,0]
    Forest: {0-1}, {2}, {3}, {4}, {5}

  3. Union(2, 3)

    Roots: 2 and 3, both rank 0. Attach 3 under 2, increment rank[2].
    parent = [0,0,2,2,4,5], rank = [1,0,1,0,0,0]
    Forest: {0-1}, {2-3}, {4}, {5}

  4. Union(4, 5)

    Roots: 4 and 5, both rank 0. Attach 5 under 4, increment rank[4].
    parent = [0,0,2,2,4,4], rank = [1,0,1,0,1,0]
    Forest: {0-1}, {2-3}, {4-5}

  5. Union(0, 2)

    Roots: 0 (rank 1) and 2 (rank 1). Equal rank — attach 2 under 0, increment rank[0].
    parent = [0,0,0,2,4,4], rank = [2,0,1,0,1,0]
    Forest: {0-1-2-3}, {4-5}

  6. Find(3)

    Path: 3 → 2 → 0 (root). With path compression, set parent[3] = 0.
    parent = [0,0,0,0,4,4]
    Node 3 now points directly to 0 — future finds are instant.

  7. Union(3, 5)

    Find(3) = 0 (instant, already compressed). Find(5) = 4.
    rank[0] = 2 > rank[4] = 1, so attach 4 under 0.
    parent = [0,0,0,0,0,4], rank = [2,0,1,0,1,0]
    All six elements now in one component!

Nearly Constant Time: The Inverse Ackermann Function

Amortized complexity

With both union by rank and path compression, a sequence of m operations on n elements takes O(m · α(n)) total time, where α is the inverse Ackermann function.

The Ackermann function grows phenomenally fast — faster than exponential, faster than tetration (towers of exponents). Its inverse, α(n), grows correspondingly slowly. How slowly?

How slow is α(n)?

α(1)         = 0
α(2)         = 1
α(4)         = 2
α(16)        = 3
α(65536)     = 4
α(2^65536)   = 5    ← a number with ~20,000 digits

For any n that fits in the observable universe, α(n) ≤ 4.

In practice, α(n) is never more than 4 for any input you'll ever encounter. So Union-Find operations are effectively O(1) amortized.

This result was proved by Robert Tarjan in 1975, and the matching lower bound (you can't do better) was proved by Fredman and Saks in 1989.

Complete Pseudocode

// Initialize n elements as singletons
function MakeSet(x):
    parent[x] = x
    rank[x] = 0
    size[x] = 1

// Find with path compression
function Find(x):
    if parent[x] != x:
        parent[x] = Find(parent[x])
    return parent[x]

// Union by rank
function Union(x, y):
    rootX = Find(x)
    rootY = Find(y)
    if rootX == rootY: return false    // already connected

    if rank[rootX] < rank[rootY]:
        swap(rootX, rootY)

    parent[rootY] = rootX             // attach smaller under larger
    size[rootX] += size[rootY]

    if rank[rootX] == rank[rootY]:
        rank[rootX] += 1

    return true                        // merge happened

Application: Kruskal's Minimum Spanning Tree

The most famous application of Union-Find is Kruskal's algorithm for finding the minimum spanning tree of a graph. The idea is beautifully simple:

  1. Sort all edges by weight

    Cheapest edges first.

  2. Initialize Union-Find

    MakeSet for every vertex.

  3. Greedily add edges

    For each edge (u, v) in sorted order: if Find(u) != Find(v), add the edge to the MST and call Union(u, v). Otherwise, skip it — it would create a cycle.

  4. Stop when you have n-1 edges

    That's a spanning tree.

Kruskal's with Union-Find

Edges sorted by weight:
  (A,B,1)  (B,C,2)  (A,C,3)  (C,D,4)  (B,D,5)

Step 1: Add (A,B,1) — Find(A)!=Find(B), union them. MST cost: 1 Step 2: Add (B,C,2) — Find(B)!=Find(C), union them. MST cost: 3 Step 3: Skip (A,C,3) — Find(A)==Find(C), would create cycle! Step 4: Add (C,D,4) — Find(C)!=Find(D), union them. MST cost: 7 Done — 3 edges for 4 vertices.

Total MST weight: 7

Kruskal's runs in O(E log E) time — dominated by sorting the edges. The Union-Find operations are nearly free.

Where Union-Find Is Used

Application How it uses Union-Find
Kruskal's MST Detect whether adding an edge would create a cycle
Network connectivity Track which computers can reach each other as links are added
Equivalence classes Group equivalent items (e.g., accounts belonging to the same person)
Percolation Determine if a porous material lets fluid flow from top to bottom
Image processing Label connected components (regions of same-colored pixels)
Least common ancestor Tarjan's offline LCA algorithm uses Union-Find on a DFS tree

Key Takeaways

  • Union-Find tracks disjoint sets with two operations: Find (which set?) and Union (merge two sets)
  • The tree-based representation lets both operations share the work of maintaining set identities
  • Union by rank keeps trees balanced — guaranteeing O(log n) Find in the worst case
  • Path compression flattens trees during Find — making future operations faster
  • Together, they achieve O(α(n)) amortized per operation — effectively constant time
  • The inverse Ackermann function α(n) never exceeds 4 for any practical input
  • Kruskal's MST algorithm is the textbook application: sort edges, use Union-Find to reject cycles

Union-Find is a rare gem in algorithm design: a data structure where two simple heuristics — union by rank and path compression — combine to produce nearly optimal performance. The proof that it achieves O(α(n)) is one of the deepest results in the analysis of algorithms, yet the implementation fits in a dozen lines of code. That combination of simplicity and power is what makes it a staple of competitive programming and systems engineering alike.