Data structure · Graphs and disjoint sets

Union-find

Disjoint sets as a forest of parent pointers: union and find in near-constant amortized time with union by rank and path compression.

The derivations, edge cases and exercises are in the lesson Disjoint sets: union by rank and path compression. Open it full width in the playground.

On this page
  1. The idea
  2. Operations
  3. Invariants
  4. When to use it
  5. Built-in equivalents
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Each set is a tree whose root names the set. Find follows parent pointers to the root; union links one root under the other. Two elements are connected exactly when their finds return the same root.

Union by rank hangs the shorter tree under the taller one, and path compression points every node on a find path straight at the root. Together they make a sequence of m operations cost O(m α(n)), where α grows so slowly it is below 5 for any practical n.

Representation. A parent array (parent[i] = i for roots) and a rank array.

Operations

Union-find operations and their complexity
OperationTimeExtra spaceNotes
Make setO(1)O(1)
FindO(α(n)) amortizedO(1) iterative
UnionO(α(n)) amortizedO(1)Two finds plus one link.
Connected?O(α(n)) amortizedO(1)

Invariants

What stays true before and after every operation.

  • Following parent from any element reaches its set’s root, where parent[root] = root.
  • Rank is an upper bound on a root’s tree height; a root’s rank only increases when two equal ranks merge.

When to use it

Use it when

  • You merge groups and ask whether two items share a group: connected components, Kruskal’s minimum spanning tree, cycle detection in undirected graphs.
  • Edges only arrive and are never removed.

Avoid it when

  • Groups must also split (union-find cannot undo a union efficiently).
  • You need the actual path between two items, not just whether one exists (use BFS or DFS).

Built-in equivalents

What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.

C#

No disjoint-set type in .NET; two int arrays are enough.

Python

No disjoint-set type in the standard library; two lists are enough.

Java

No disjoint-set type in java.util; two int arrays are enough.

C++

No disjoint-set type in the standard library (Boost has disjoint_sets).

Step through it

The interactive lab for union-find: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Algorithms that use it

Problems, patterns and exercises

References