M28 · Union Find

Disjoint Sets: Union by Rank and Path Compression

A disjoint-set structure answers “are these two in the same group?” while groups keep merging. This lesson builds it from a parent array, shows how a naive version degrades into long chains, and adds the two fixes, union by rank and path compression, that together make every operation effectively constant time. It is the tool Kruskal’s algorithm relies on in the next module.

~40 minIntermediateC# · Python · Java · C++
Curriculum: M28 Union Find · 1 of 1 lessons available

You will be able to

  • Represent disjoint sets as a forest stored in a parent array, and read the sets off the array.
  • Trace find, union and connected, including the two passes of path compression.
  • Explain why union by rank keeps every tree’s height at most log₂ n.
  • State the O(m α(n)) amortized bound for both optimizations together and what α means in practice.
  • Use union-find for connectivity questions, cycle detection and counting components, and know what it cannot do.

Helpful before this lesson

  • M23 Graph Fundamentals — Graph vocabulary and representations, and how density changes the right choice.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

The question it answers

Elements arrive as 0 … n − 1. Over time you learn facts of the form "these two belong together": two computers got a cable, two accounts share an e-mail address, two cells of a grid were joined. At any moment you want to ask whether two elements are (directly or indirectly) in the same group, and how many groups there are.

A disjoint-set structure (also called union-find) supports exactly this:

  • find(x): the representative of x's set, one fixed member that names the whole set.
  • union(a, b): merge the sets containing a and b. Returns false if they were already one set.
  • connected(a, b): find(a) == find(b).

Groups only ever merge. There is no "split", and that restriction is what makes the structure so fast.

A forest in an array

Each set is a tree whose root is the representative. Nothing points down; every element stores only its parent, so the whole forest is a single array:

parent = [0, 0, 0, 2, 4, 4]      sets: {0, 1, 2, 3} with root 0, and {4, 5} with root 4

   0        4
  / \       |
 1   2      5
     |
     3

A root is its own parent. Initially every element is a root: parent[i] = i, n singleton sets.

  • find(x) follows parent from x until it reaches a root.
  • union(a, b) finds both roots and, if they differ, makes one root the child of the other.

The lab draws the forest with roots at the back and arrows from child to parent, and the parent array itself as the lane of plinths in front. Watch both change together.

Why the naive version is slow

Suppose union(a, b) always sets parent[find(a)] = find(b). The sequence union(0, 1), union(1, 2), union(2, 3), … then builds a single chain 0 → 1 → 2 → … → n − 1, and find(0) walks all n nodes. Repeating such finds costs Θ(n) each, Θ(m · n) for m operations. Two independent fixes bring it down to almost nothing.

Fix 1: union by rank

Give every root a rank, an upper bound on its tree's height, starting at 0. When merging two roots, hang the one with the smaller rank under the larger. Heights then do not grow at all. Only when both ranks are equal does the merged tree possibly get one level taller, so the new root's rank goes up by one.

union(a, b):
    ra = find(a), rb = find(b)
    if ra == rb: return false
    if rank[ra] < rank[rb]: swap(ra, rb)
    parent[rb] = ra
    if rank[ra] == rank[rb]: rank[ra] += 1
    return true

Tie rule used here: on equal ranks the root of the first argument stays root. Any fixed rule works; fixing one makes the exact parent array reproducible, which the shared fixture checks in all four languages.

Why height stays ≤ log₂ n. A root of rank r has at least 2ʳ elements in its tree. True for r = 0 (one element). A root reaches rank r + 1 only by absorbing another root of rank r, so its tree then has at least 2ʳ + 2ʳ = 2ʳ⁺¹ elements. Since a tree holds at most n elements, r ≤ log₂ n, and a tree's height never exceeds its root's rank. So find is O(log n) even without the second fix. The lab's Union by rank preset shows a rank-1 tree absorbing single elements without growing.

Union by size (hang the smaller set under the larger, ties as you like) gives the same log₂ n height bound and the same overall complexity. Some people prefer it because the size of each set is often useful on its own. This lesson uses rank, the version the classic analysis is written for.

Fix 2: path compression

find has just walked from x to the root; every node on that path could point straight at the root instead. Doing so costs only a constant factor more now and makes later finds from any of them one hop:

find(x):
    root = x
    while parent[root] != root:       # pass 1: walk up
        root = parent[root]
    while parent[x] != root:          # pass 2: re-point the path
        next = parent[x]
        parent[x] = root
        x = next
    return root

The Path compression preset builds a tree of height 2 and then calls find(3) twice. The first call walks 3 → 2 → 0 and rewires parent[3] to 0 (one pointer rewrite). The second call takes a single hop. Note that compression does not update ranks: after compression a rank is only an upper bound on the height, which is all the analysis needs.

Two well-known one-pass alternatives, path halving (point every other node at its grandparent) and path splitting (point every node at its grandparent), have the same asymptotic bound and avoid the second loop. The two-pass version is the easiest to reason about, so it is the one shown here. The implementations are iterative on purpose: a recursive find is shorter but can hit Python's recursion limit before the tree is flattened.

How fast is it?

Version One find (worst case) m operations on n elements
Naive linking O(n) O(m · n)
Union by rank only O(log n) O(m log n)
Path compression only O(n) for one call O(m log n) amortized (Tarjan and van Leeuwen)
Both O(log n) for one call O(m α(n)) amortized (Tarjan, 1975)

α(n) is the inverse Ackermann function. The Ackermann function grows so explosively that its inverse is at most 4 for any n that could ever be written down in a computer, so in practice each operation costs a small constant on average. It is still not literally constant: Fredman and Saks proved in 1989 that no structure for this problem can beat Θ(α(n)) amortized per operation in their cell-probe model, so union by rank plus path compression is optimal.

"Amortized" matters: a single find can still take O(log n) steps, but the compression it performs pays for the later cheap ones. Space is O(n): two integer arrays.

What it is good for

  • Connectivity as edges arrive. Process edges one at a time with union; connected answers reachability at any point. The Connectivity queries preset does this.
  • Counting components. Start with n, subtract one for every union that returns true.
  • Cycle detection in an undirected graph. An edge whose endpoints are already connected closes a cycle: union returns false.
  • Kruskal's minimum spanning tree (next module, M27): take edges from lightest to heaviest and keep each one whose union succeeds. Union-find is the reason that loop is fast.
  • Equivalence classes in general: merging duplicate accounts, grouping pixels of the same region, unifying types in a compiler.

What it cannot do: split a set, delete an element, or list a set's members without scanning everything. Deleting edges needs other structures (dynamic connectivity), and an "undo" variant must give up path compression to remain fast.

The teaching implementation

The class keeps parent, rank and a set count. Find, Union and Connected are exactly the pseudocode above, in the same order in all four languages, so the lab can highlight the matching lines. The listings are the files the tests run: each language replays one shared fixture of find / union / connected sequences and checks the return values, the exact parent array after compression, and the set count; then it runs 300 random operation lists against a naive reference that stores a component label per element and relabels a whole component on every merge. The naive version is O(n) per union, but obviously correct, which is what a reference should be.

Language notes

Language Notes
C# int[] arrays; the swap is a tuple assignment (ra, rb) = (rb, ra). No disjoint-set type in .NET.
Python Lists; the compression step uses tuple assignment self.parent[x], x = root, self.parent[x], which evaluates the right side before assigning. No standard-library equivalent.
Java int[] arrays and a manual swap. No disjoint-set type in the JDK.
C++ union is a keyword, so the method is unite. Indices are std::size_t; std::iota fills the initial parents. The standard library has none; Boost provides boost::disjoint_sets.

Common mistakes

  • Linking the elements instead of their roots: parent[b] = a merges only b's subtree at best and corrupts the forest at worst. Always link find(a) and find(b).
  • Comparing parent[a] == parent[b] to test connectivity. Two elements can share a root without sharing a parent. Compare find(a) == find(b).
  • Updating ranks during compression, or incrementing rank on every union rather than only on ties.
  • Forgetting the ra == rb check: a node linked to itself is a root, but your set count drops by one for nothing.

Edge cases

  • union(x, x) returns false and changes nothing.
  • find on a root returns it after one check; no compression happens.
  • A single element: one set, find(0) = 0.
  • Out-of-range elements are a caller error; the lab rejects them, the listings rely on array bounds.

Worked practice

1. Start with 4 singletons and run union(2, 3), union(0, 1), union(3, 1). What is the parent array?

Answer

union(2, 3): equal ranks, 3 goes under 2, rank[2] = 1. union(0, 1): 1 under 0, rank[0] = 1. union(3, 1): find(3) = 2, find(1) = 0, ranks are equal (1 and 1), so the first argument's root 2 stays root and 0 goes under it: rank[2] = 2. Parent array [2, 0, 2, 2]. (After find(1) compresses, it becomes [2, 2, 2, 2]; this is the fixture's equal-rank-tie case.)

2. Why does a rank-r root have at least 2ʳ elements, even after path compression?

Answer

Compression only moves nodes within one tree; it never changes which elements belong to a root's set, and it never changes ranks. The size argument is about set sizes at the moment a rank increases, so it still holds.

3. You add the edges of an undirected graph one by one. How do you detect the first edge that creates a cycle?

Answer

Call union(u, v) for each edge; the first call that returns false joins two nodes that were already connected, so that edge closes a cycle.

Summary

  • Disjoint sets are a forest stored in a parent array; a root is its own parent and names its set.
  • find walks to the root; union links two roots; connected compares roots.
  • Union by rank keeps height ≤ log₂ n; path compression flattens the paths that find walks.
  • Together: O(m α(n)) for m operations, effectively constant per operation; O(n) space.
  • It only merges. That is enough for connectivity, component counting, cycle detection and Kruskal.

Full implementation

Union-find in four languages, each checked against one shared fixture of find, union and connected sequences (return values, the exact parent array after path compression and the set count) and 300 random operation lists compared with naive component labels.

namespace Bekadan.Dsa.Examples.Graphs;
 
/// <summary>
/// Disjoint-set union over 0..n-1 with union by rank and full path compression.
/// On equal ranks the first argument's root stays root. Any sequence of m
/// operations takes O(m α(n)) time, where α is the inverse Ackermann function.
/// </summary>
public sealed class UnionFind
{
    private readonly int[] _parent;
    private readonly int[] _rank;
 
    public int Count { get; private set; }
 
    public UnionFind(int size)
    {
        _parent = new int[size];
        _rank = new int[size];
        for (int i = 0; i < size; i++)
            _parent[i] = i;
        Count = size;
    }
 
    public int Parent(int x) => _parent[x];
 
    public int Find(int x)
    {
        int root = x;
        while (_parent[root] != root)
            root = _parent[root];
        while (_parent[x] != root)
        {
            int next = _parent[x];
            _parent[x] = root;
            x = next;
        }
        return root;
    }
 
    public bool Union(int a, int b)
    {
        int ra = Find(a);
        int rb = Find(b);
        if (ra == rb)
            return false;
        if (_rank[ra] < _rank[rb])
            (ra, rb) = (rb, ra);
        _parent[rb] = ra;
        Count--;
        if (_rank[ra] == _rank[rb])
            _rank[ra]++;
        return true;
    }
 
    public bool Connected(int a, int b)
    {
        return Find(a) == Find(b);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Graphs/UnionFind.cs

"""Disjoint-set union over 0..n-1 with union by rank and full path compression.
 
On equal ranks the first argument's root stays root. Any sequence of m operations
takes O(m * alpha(n)) time, where alpha is the inverse Ackermann function.
"""
 
 
class UnionFind:
    def __init__(self, size: int) -> None:
        self.parent = list(range(size))
        self.rank = [0] * size
        self.count = size
 
    def find(self, x: int) -> int:
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:
            self.parent[x], x = root, self.parent[x]
        return root
 
    def union(self, a: int, b: int) -> bool:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.count -= 1
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        return True
 
    def connected(self, a: int, b: int) -> bool:
        return self.find(a) == self.find(b)

Tested on CPython 3.14.0 · examples/python/dsa_examples/union_find.py

package dev.bekadan.dsa.graphs;
 
/**
 * Disjoint-set union over 0..n-1 with union by rank and full path compression. On equal
 * ranks the first argument's root stays root. Any sequence of m operations takes
 * O(m α(n)) time, where α is the inverse Ackermann function.
 */
public final class UnionFind {
    private final int[] parent;
    private final int[] rank;
    private int count;
 
    public UnionFind(int size) {
        parent = new int[size];
        rank = new int[size];
        for (int i = 0; i < size; i++) {
            parent[i] = i;
        }
        count = size;
    }
 
    /** Number of disjoint sets. */
    public int count() {
        return count;
    }
 
    public int parent(int x) {
        return parent[x];
    }
 
    public int find(int x) {
        int root = x;
        while (parent[root] != root) {
            root = parent[root];
        }
        while (parent[x] != root) {
            int next = parent[x];
            parent[x] = root;
            x = next;
        }
        return root;
    }
 
    public boolean union(int a, int b) {
        int ra = find(a);
        int rb = find(b);
        if (ra == rb) {
            return false;
        }
        if (rank[ra] < rank[rb]) {
            int t = ra;
            ra = rb;
            rb = t;
        }
        parent[rb] = ra;
        count--;
        if (rank[ra] == rank[rb]) {
            rank[ra]++;
        }
        return true;
    }
 
    public boolean connected(int a, int b) {
        return find(a) == find(b);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/graphs/UnionFind.java

#pragma once
 
#include <cstddef>
#include <numeric>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// Disjoint-set union over 0..n-1 with union by rank and full path compression. On equal
// ranks the first argument's root stays root. Any sequence of m operations takes
// O(m α(n)) time, where α is the inverse Ackermann function.
class UnionFind {
public:
    explicit UnionFind(std::size_t size) {
        parent_.resize(size);
        std::iota(parent_.begin(), parent_.end(), std::size_t{0});
        rank_.assign(size, 0);
        count_ = size;
    }
 
    [[nodiscard]] std::size_t count() const noexcept { return count_; }
    [[nodiscard]] std::size_t parent(std::size_t x) const { return parent_[x]; }
 
    std::size_t find(std::size_t x) {
        std::size_t root = x;
        while (parent_[root] != root) root = parent_[root];
        while (parent_[x] != root) {
            const std::size_t next = parent_[x];
            parent_[x] = root;
            x = next;
        }
        return root;
    }
 
    bool unite(std::size_t a, std::size_t b) {  // `union` is a C++ keyword
        std::size_t ra = find(a);
        std::size_t rb = find(b);
        if (ra == rb) return false;
        if (rank_[ra] < rank_[rb]) std::swap(ra, rb);
        parent_[rb] = ra;
        --count_;
        if (rank_[ra] == rank_[rb]) ++rank_[ra];
        return true;
    }
 
    bool connected(std::size_t a, std::size_t b) {
        return find(a) == find(b);
    }
 
private:
    std::vector<std::size_t> parent_;
    std::vector<int> rank_;
    std::size_t count_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/union_find.hpp

References