Union find · near-constant amortized (inverse Ackermann)

Union-find

Union by rank and path compression on a forest and its parent array.

The full explanation, derivation and practice are in the lesson Disjoint sets: union by rank and path compression.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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