Union-Find (Disjoint Set) in C, C++ and Python: Path Compression and Union by Rank

Build a union-find (disjoint set) in C, C++ and Python, and see how path compression and union by rank cut find depth from 9,999 hops to 1.

Three small trees of dark round nodes on a light gray background: one with a blue curved shortcut from its lowest node straight to its blue root, and two trees whose roots are joined by a green edge.

Union-Find answers one question fast: are these two elements in the same set? It keeps a forest of trees, one tree per set. find walks up to the root and union links two roots. Left alone, a tree can grow into a long chain, and two classic heuristics prevent that: union by rank keeps trees shallow, and path compression flattens every path a find walks. On 10,000 elements joined by 9,999 chain unions, the final finds walked 49,995,000 parent hops with neither heuristic and 9,999 with union by rank.

This guide covers the parent array, both heuristics and why they work together, the near-constant amortized bound, and implementations in C, C++ and Python. Union-Find is the structure behind Kruskal’s minimum spanning tree, percolation, image segmentation and incremental connectivity, and the whole type fits in a few dozen lines. The companion code includes tests, a depth experiment and five pitfalls. It was compiled and run on Ubuntu 24.04 with GCC 13.3, Clang 18.1.3 and Python 3.12, and on Windows 11 with MSVC 19.44 and Python 3.14. All three languages print byte-identical demo output.

What Is Union-Find?

**Union-Find, or the disjoint-set forest, is a data structure that keeps a collection of disjoint sets under two operations: find(x) returns the representative of the set containing x, and union(a, b) merges the sets containing a and b. It answers “are a and b connected?” in near-constant amortized time and is the standard structure for incremental connectivity.**

The problem it solves is dynamic connectivity. Edges of a graph arrive one at a time, and the program must say whether two vertices are already connected. A minimum spanning tree algorithm must reject edges that would close a cycle. An image segmenter merges neighboring regions as it scans. Each of these is a stream of unions mixed with connectivity queries, and every query must stay cheap after millions of merges. Merging sets by copying lists costs O(n) per union. Storing each set as a tree of parent pointers makes a find cost O(depth), and the depth is what the two heuristics control.

A third operation comes for free: connected(a, b) is just find(a) == find(b). The number of components is a counter that starts at n and drops by one on every union that joins two different roots. The types also expose rank and tree size for the demo and the tests.

The Graph article answers connectivity on a fixed graph with BFS and DFS. Union-Find is the tool when edges keep arriving. Its best-known use is Kruskal’s algorithm, which sorts the edges, calls union on each one and rejects every edge whose endpoints already share a set.

A tree stored as a parent array Eight elements with root 0. The blue parent values are the path that find(7) walks. index parent 0 0 1 0 2 0 3 1 4 1 5 4 6 5 7 6 0 1 2 3 4 5 6 7 find(7) walks 7-6-5-4-1-0 After full compression, nodes 7, 6, 5 and 4 point straight at root 0, and the next find(7) is one hop.
Figure 1: The parent array and the tree it encodes. A find walks parent pointers to the root, and full path compression then points every node on that path straight at the root, so the next find takes one hop.

How This Was Measured

SettingValue
Date testedDecember 5, 2026
HardwareIntel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300
Operating systemUbuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Windows 11 for the MSVC and Windows Python runs
Compilers and runtimesGCC 13.3 and Clang 18.1.3 at -O2, MSVC 19.44 at /W4 /WX, Python 3.12.3 (Linux captures) and Python 3.14.6 (Windows tests)
Depth experiment10,000 elements, 9,999 chain unions union(i, i + 1), then one find of every element under each policy
PoliciesNeither heuristic, compression only, rank only, both
What is countedParent hops during the final finds. total_hops sums them, max_depth is the longest single find, avg_depth divides the total by 10,000
StatisticDeterministic counts, identical on every run and in all three languages
CheckAll four policies use the same union sequence and the same tie rule, and the C, C++ and Python experiments must print the same table

The counts are deterministic, so there is no timing noise to control. This article measures depth rather than wall time because depth is what the heuristics change, and it reproduces on any machine. The chain sequence is the worst case for the bare forest. It is an easy case for union by rank, as the results section explains.

The Forest Representation and Three Operations

Each element stores one integer, its parent. A root is an element whose parent is itself. A set is the tree hanging from a root, and the root is the set’s representative. find(x) follows parent pointers until it reaches a root, and union(a, b) finds both roots and makes one point at the other. That is the whole representation: one array of indexes, no pointers and no allocation after initialization.

A find costs the depth of x, and a union costs two finds. A forest built by careless unions can become a chain of n nodes, so a single find can be O(n). With union by rank the depth is at most log2(n), and with both heuristics the amortized cost per operation drops to O(alpha(n)). The rest of the design is about keeping those bounds true.

The C and C++ versions keep three arrays, parent, rank and size, and the Python class keeps three lists with the same contract. Rank drives the union decision. Size counts the elements in each tree and is kept as a diagnostic. Both are meaningful only on roots.

Union by Rank

Union by rank attaches the shallower tree under the deeper one. Every root starts with rank 0. When two roots of different rank merge, the higher rank becomes the new root and no rank changes. When two roots of equal rank merge, one becomes the root and its rank goes up by one. Rank is an upper bound on the tree’s height, not its exact height, which is why path compression can flatten a tree without the ranks becoming wrong.

The property that matters is a size bound. A root of rank r has at least 2^r elements in its tree, because a rank r root only appears when two rank r – 1 trees merge, and each of those already holds at least 2^(r – 1) elements. So rank never exceeds log2(n), and neither does the height of any tree.

Union by size is the common alternative: attach the root with fewer elements under the root with more. It gives the same logarithmic bound. The code in this article links by rank and keeps size only for diagnostics, so both numbers are available in the demo.

Same unions, two shapes Seven elements and the unions union(0, 1), union(1, 2), …, union(5, 6). Arrows point from child to parent. Without rank: the root of the first argument goes under the root of the second 0 1 2 3 4 5 6 root A chain of depth 6: find(0) walks six parent pointers. With n elements it walks n – 1. Union by rank: the lower-rank root goes under the higher-rank root 0 root, rank 1 1 2 3 4 5 6
Figure 2: The same six chain unions with and without union by rank. Without rank they build a chain of depth 6. With rank, each new singleton goes under the existing root and the tree stays a star of depth 1.

Path Compression

Path compression changes the tree during find. Once the walk reaches the root, every node on the path is pointed straight at the root, so the next find of any of them takes one hop. The iterative version walks the path twice: once to find the root and once to rewrite the parents. A recursive version is shorter but needs one stack frame per hop, which is the subject of the first pitfall.

Compression alone does not bound the height of a tree. The first find of a deep node still walks the whole path, and later unions can build new depth. What compression does is make that walk a one-time cost, because every node it passes ends up one hop from the root.

The two heuristics are independent. Rank decides where a merged root goes, and compression rewrites paths that finds have already walked. Each one improves the bare forest on its own, and together they give the inverse-Ackermann bound.

Combining Both: Near-Constant Find

With union by rank and path compression together, any sequence of m operations on n elements costs O(m alpha(n)), where alpha is the inverse Ackermann function. Alpha grows so slowly that it stays at 4 or less for any n a computer can store, so in practice each operation costs a small constant, even though one particular find can still walk a long path.

The proof is hard, but using the bound is not. The bound is amortized over the whole sequence rather than promised for each operation: a find that flattens a long path pays for the cheap finds that follow it. That is why union-find is so often the right answer for connectivity. The total work is bounded by the number of operations, whatever shape any single tree takes along the way.

Union calls find on both arguments, so unions compress paths too. A workload heavy on merges benefits as much as one heavy on queries, and the implementation never needs to know which kind it is serving.

The structure and its variants are described on Wikipedia, the common variants and their analysis on cp-algorithms, and the classic presentation in Princeton’s Algorithms course material.

Union-Find Implementation in C

The C type is a struct with three int arrays and a component count. Initialization allocates the arrays and makes every element its own root, with rank 0 and size 1. The find is iterative and compresses the path in a second walk. The union touches only the two roots.

bool uf_init(UnionFind *uf, int n)
{
    int index;

    uf->parent = NULL;
    uf->rank = NULL;
    uf->size = NULL;
    uf->count = 0;
    uf->elements = 0;
    if (n < 1)
        return false;
    if ((size_t)n > SIZE_MAX / sizeof *uf->parent)
        return false;
    uf->parent = malloc((size_t)n * sizeof *uf->parent);
    uf->rank = malloc((size_t)n * sizeof *uf->rank);
    uf->size = malloc((size_t)n * sizeof *uf->size);
    if (uf->parent == NULL || uf->rank == NULL || uf->size == NULL) {
        free(uf->parent);
        free(uf->rank);
        free(uf->size);
        uf->parent = NULL;
        uf->rank = NULL;
        uf->size = NULL;
        return false;
    }
    for (index = 0; index < n; ++index) {
        uf->parent[index] = index;
        uf->rank[index] = 0;
        uf->size[index] = 1;
    }
    uf->count = n;
    uf->elements = n;
    return true;
}
int uf_find(UnionFind *uf, int x)
{
    int root;
    int next;

    if (uf->parent == NULL || x < 0 || x >= uf->elements)
        return -1;
    root = x;
    while (uf->parent[root] != root)
        root = uf->parent[root];
    while (x != root) {
        next = uf->parent[x];
        uf->parent[x] = root;
        x = next;
    }
    return root;
}
bool uf_union(UnionFind *uf, int a, int b)
{
    int root_a = uf_find(uf, a);
    int root_b = uf_find(uf, b);

    if (root_a < 0 || root_b < 0 || root_a == root_b)
        return false;
    if (uf->rank[root_a] < uf->rank[root_b]) {
        uf->parent[root_a] = root_b;
        uf->size[root_b] += uf->size[root_a];
    } else {
        uf->parent[root_b] = root_a;
        uf->size[root_a] += uf->size[root_b];
        if (uf->rank[root_a] == uf->rank[root_b])
            uf->rank[root_a]++;
    }
    uf->count--;
    return true;
}

Output:

union-find with 6 elements
union 0,1 -> true, components 5
union 2,3 -> true, components 4
union 1,3 -> true, components 3
union 0,3 -> false, components 3
union 4,5 -> true, components 2
connected 0,2 -> true, connected 0,4 -> false
union 0,5 -> true, components 1
find 0 -> 0, find 5 -> 0
root 0: rank 2, size 6

Union-Find Implementation in C++

The C++ version is a class over std::vector<int>. The algorithms are the same, the vectors own the storage, and the constructor rejects an element count below 1. An out-of-range index makes find throw and makes union_sets return false.

    explicit UnionFind(int element_count)
        : component_count_(element_count)
    {
        if (element_count < 1)
            throw std::invalid_argument("UnionFind: element count must be at least 1");
        const std::size_t count = static_cast<std::size_t>(element_count);
        parent_.resize(count);
        rank_.assign(count, 0);
        size_.assign(count, 1);
        for (std::size_t i = 0; i < count; ++i)
            parent_[i] = static_cast<int>(i);
    }

    // Root of x with full path compression. Every node on the path from x to
    // the root points at the root afterwards.
    [[nodiscard]] int find(int x)
    {
        if (!in_range(x))
            throw std::out_of_range("UnionFind::find: element index out of range");
        int root = x;
        while (parent_[root] != root)
            root = parent_[root];
        // Second walk: flatten the path. The loop stops at the root, which
        // already points at itself.
        while (parent_[x] != x) {
            const int next = parent_[x];
            parent_[x] = root;
            x = next;
        }
        return root;
    }

    // Merges the sets that hold a and b and returns true; returns false when the
    // two elements are already in one set or either index is out of range.
    [[nodiscard]] bool union_sets(int a, int b)
    {
        if (!in_range(a) || !in_range(b))
            return false;
        int root_a = find(a);
        int root_b = find(b);
        if (root_a == root_b)
            return false;
        if (rank_[root_a] < rank_[root_b])
            std::swap(root_a, root_b);
        if (rank_[root_a] == rank_[root_b])
            ++rank_[root_a];
        parent_[root_b] = root_a;
        size_[root_a] += size_[root_b];
        --component_count_;
        return true;
    }

The C++ demo prints the same nine lines as the C program, byte for byte.

Union-Find Implementation in Python

The Python class keeps three lists and the same contract. Its find is iterative for the same reason as the C version: Python’s default recursion limit of 1,000 is far shorter than a chain the heuristics have not yet fixed, which the fifth pitfall shows.

    def find(self, x: int) -> int:
        """Return the root of x, and point every element on the path at it.

        An out of range x returns -1 and changes nothing.  The walk is
        iterative: a parent chain can be 10,000 links long before the first
        compression, and recursion would exhaust the interpreter's stack.
        """
        if not self._valid(x):
            return -1
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:
            parent = self.parent[x]
            self.parent[x] = root
            x = parent
        return root

    def union_sets(self, a: int, b: int) -> bool:
        """Merge the sets of a and b, reporting whether a merge happened.

        The smaller rank is attached under the larger rank; equal ranks attach
        the root of b under the root of a and increment the rank of a's root.
        Already connected elements, and an index outside the forest, report
        False and change nothing, so the component count never goes below the
        real number of sets.
        """
        if not self._valid(a) or not self._valid(b):
            return False
        root_a = self.find(a)
        root_b = self.find(b)
        if root_a == root_b:
            return False
        if self.rank[root_a] < self.rank[root_b]:
            root_a, root_b = root_b, root_a
        self.parent[root_b] = root_a
        self.size[root_a] += self.size[root_b]
        if self.rank[root_a] == self.rank[root_b]:
            self.rank[root_a] += 1
        self._component_count -= 1
        return True

Output (Python demo):

union-find with 6 elements
union 0,1 -> true, components 5
union 2,3 -> true, components 4
union 1,3 -> true, components 3
union 0,3 -> false, components 3
union 4,5 -> true, components 2
connected 0,2 -> true, connected 0,4 -> false
union 0,5 -> true, components 1
find 0 -> 0, find 5 -> 0
root 0: rank 2, size 6

Measured: Find Depth With Neither, One and Both

The experiment creates 10,000 elements and performs the chain unions union(i, i + 1) for i from 0 to 9,998. It then calls the policy’s find on every element and counts parent hops. All four policies share the union sequence and the tie rule, so the only difference is the heuristic under test. Without rank, the union puts the root of the first argument under the root of the second.

static int find_compress(Forest *forest, int x, int *hops)
{
    int root = x;
    int next;

    while (forest->parent[root] != root) {
        root = forest->parent[root];
        ++*hops;
    }
    while (x != root) {
        next = forest->parent[x];
        forest->parent[x] = root;
        x = next;
    }
    return root;
}
static void union_by_rank(Forest *forest, int a, int b, bool compress)
{
    int hops = 0;
    int root_a = policy_find(forest, a, &hops, compress);
    int root_b = policy_find(forest, b, &hops, compress);

    if (root_a == root_b)
        return;
    if (forest->rank[root_a] < forest->rank[root_b]) {
        forest->parent[root_a] = root_b;
    } else {
        forest->parent[root_b] = root_a;
        if (forest->rank[root_a] == forest->rank[root_b])
            forest->rank[root_a]++;
    }
}

Output (C, identical in C++ and Python):

10,000 elements, chain unions i with i+1
policy            total_hops  max_depth  avg_depth
neither             49995000       9999    4999.50
compression only       19997       9999       2.00
rank only               9999          1       1.00
both                    9999          1       1.00

Without either heuristic the forest is one chain. The final finds total 49,995,000 hops, the longest walks all 9,999 parent pointers, and the average is 4,999.50: the quadratic cost of this union order made visible. Compression alone cuts the total to 19,997 and the average to 2.00, but its longest find is still 9,999. The first final find pays for the whole chain and flattens it, and every later find takes one hop. Union by rank alone, and both heuristics together, finish with every element one hop from the root.

The rank result says more about this input than about rank. Each chain union merges the growing tree with a new singleton, so union by rank hangs the singleton directly under the existing root and the forest ends as a star of depth 1. The logarithmic height bound is a worst-case guarantee for other union orders, and this sequence never approaches it. What the table shows is the order of magnitude, thousands of hops against one or two, and that each heuristic removes a different cost.

Final find cost after 9,999 chain unions 10,000 elements, then one find of every element. Linear scales, values printed on each bar. Deepest single find (parent hops) Average hops per find neither 9,999 4,999.50 compression only 9,999 2.00 rank only 1 1.00 both 1 1.00 Compression alone pays the whole chain once, in the first find, and then averages two hops.
Figure 3: Final find cost after 9,999 chain unions for the four policies: the longest single find and the average hops per find, on linear scales.

Five Ways Union-Find Passes a Quick Test and Still Fails

Each program below compiles and prints something plausible until the output line that gives it away, or until a sanitizer or the Python runtime stops it. The C pitfalls are in the C repository’s pitfalls/ directory, the C++ ones in the C++ repository and the Python one in the Python repository, and the workflows rerun each and check the line or the failure it should produce.

1. A Recursive Find on a Deep Chain

static int find_recursive(const int *parent, int x)
{
    int root;

    if (parent[x] == x)
        return x;
    root = find_recursive(parent, parent[x]);   /* AddressSanitizer stops here. */
    return root;
}

int main(void)
{
    int *parent;
    int index;

    setvbuf(stdout, NULL, _IONBF, 0);
    puts("recursive_find: one stack frame per parent hop overflows on a "
         "2,000,000-node chain");
    parent = malloc((size_t)ELEMENTS * sizeof *parent);
    if (parent == NULL) {
        fputs("recursive_find: out of memory\n", stderr);
        return EXIT_FAILURE;
    }
    for (index = 0; index < ELEMENTS; ++index)
        parent[index] = index;
    for (index = 0; index + 1 < ELEMENTS; ++index)
        parent[index] = index + 1;   /* the chain 0 -> 1 -> ... -> 1999999 */
    puts("chain built: find(0) has 1999999 parent hops before it recurses to "
         "the root");
    printf("find(0) -> %d\n", find_recursive(parent, 0));
    free(parent);
    return EXIT_SUCCESS;
}

Output:

recursive_find: one stack frame per parent hop overflows on a 2,000,000-node chain
chain built: find(0) has 1999999 parent hops before it recurses to the root

AddressSanitizer stops the program inside the recursion. Its report, summarized:

AddressSanitizer:DEADLYSIGNAL
ERROR: AddressSanitizer: stack-overflow in find_recursive, called from find_recursive
SUMMARY: AddressSanitizer: stack-overflow pitfalls/recursive_find.c:26 in find_recursive

One stack frame per parent hop is fine for a shallow tree and fatal for a chain. On this 2,000,000-node chain the recursion would need 1,999,999 nested calls, and the stack overflows long before the root. The fix is the iterative two-walk find used throughout this article, which needs one stack frame and walks a path that compression rewrites anyway. The pitfall is built at -O0 under AddressSanitizer, because an optimizing compiler can turn this tail call into a loop and hide the bug.

2. A Find Without Compression

static int find_walk(const int *parent, int x, int *hops)
{
    while (parent[x] != x) {
        x = parent[x];
        ++*hops;
    }
    return x;
}

/* The fix: a second pass points every node on the path straight at the root. */
static int find_compress(int *parent, int x, int *hops)
{
    int root = x;
    int next;

    while (parent[root] != root) {
        root = parent[root];
        ++*hops;
    }
    while (x != root) {
        next = parent[x];
        parent[x] = root;
        x = next;
    }
    return root;
}

Output:

no_compression: union ignores rank and find never compresses, so the chain stays deep
10000 elements chained by union(i, i+1): parent[i] = i + 1 up to the last
find(0) without compression: 9999 hops to root 9999
the first compressed find(0): 9999 hops, then the path is flat
the next find(0): 1 hop, same root 9999

Without compression, a find on the 10,000-node chain walks 9,999 parent pointers every time it runs. The program contrasts that with a compressed find. The first compressed find also walks 9,999 hops but flattens the path, so the next find takes 1 hop. The cost is paid once instead of on every query, which is the whole idea of compression.

3. A Rank That Never Grows

void unite_missing_increment(std::vector<int>& parent, const std::vector<int>& rank,
                             int a, int b)
{
    int root_a = find_root(parent, a);
    int root_b = find_root(parent, b);
    if (root_a == root_b)
        return;
    if (rank[static_cast<std::size_t>(root_a)]
        < rank[static_cast<std::size_t>(root_b)]) {
        const int swap = root_a;
        root_a = root_b;
        root_b = swap;
    }
    // BUG: the increment of root_a's rank is missing. Every rank stays 0.
    parent[static_cast<std::size_t>(root_b)] = root_a;
}

// The correct merge: equal ranks raise the rank of the root that keeps the set.
void unite_by_rank(std::vector<int>& parent, std::vector<int>& rank, int a, int b)
{
    int root_a = find_root(parent, a);
    int root_b = find_root(parent, b);
    if (root_a == root_b)
        return;
    if (rank[static_cast<std::size_t>(root_a)]
        < rank[static_cast<std::size_t>(root_b)]) {
        const int swap = root_a;
        root_a = root_b;
        root_b = swap;
    }
    if (rank[static_cast<std::size_t>(root_a)]
        == rank[static_cast<std::size_t>(root_b)]) {
        ++rank[static_cast<std::size_t>(root_a)];
    }
    parent[static_cast<std::size_t>(root_b)] = root_a;
}

// The deepest final find: the largest number of parent hops over all elements.
int max_depth(const std::vector<int>& parent)
{
    int deepest = 0;
    for (int x = 0; x < kElements; ++x) {
        int hops = 0;
        int current = x;
        while (parent[static_cast<std::size_t>(current)] != current) {
            current = parent[static_cast<std::size_t>(current)];
            ++hops;
        }
        if (hops > deepest)
            deepest = hops;
    }
    return deepest;
}

Output:

missing_rank_increment: rank is never incremented, so every merge looks like a tie
ordered unions: union(i, i - 1) for i = 1 to 9999
max depth with the missing increment: 9999
max depth with union by rank: 1

The broken union compares ranks correctly but never raises a rank on a tie. Every rank stays 0, so every merge is a tie, and the tie rule puts the existing tree under the new singleton each time. The ordered unions build a chain with a maximum depth of 9,999, against 1 with the correct increment. The rank is the state that makes the height bound true, and one missing line loses it.

4. A Component Count Decremented Twice

bool union_with_double_decrement(std::vector<int>& parent, int& components, int a, int b)
{
    const int root_a = find_root(parent, a);
    const int root_b = find_root(parent, b);
    const bool merged = root_a != root_b;
    if (merged)
        parent[static_cast<std::size_t>(root_a)] = root_b;
    --components;
    return merged;
}

}  // namespace

int main()
{
    constexpr int kElements = 4;
    std::vector<int> parent(static_cast<std::size_t>(kElements));
    for (int i = 0; i < kElements; ++i)
        parent[static_cast<std::size_t>(i)] = i;
    int components = kElements;

    std::cout << "double_decrement: a union of an already connected pair decrements "
                 "the count again\n";
    union_with_double_decrement(parent, components, 0, 1);
    union_with_double_decrement(parent, components, 1, 2);
    union_with_double_decrement(parent, components, 2, 3);
    std::cout << "component count before the double union: " << components << '\n';

    // 0, 1, 2 and 3 are one set now, so this call merges nothing and must not
    // change the count. The broken function decrements it anyway.
    const bool merged = union_with_double_decrement(parent, components, 0, 2);
    std::cout << "union 0,2 returned " << (merged ? "true" : "false")
              << ", component count after the double union: " << components << '\n';
    std::cout << "the real number of sets: " << count_sets(parent) << '\n';

    union_with_double_decrement(parent, components, 1, 3);
    std::cout << "component count after a second double union: " << components << '\n';

    return EXIT_SUCCESS;
}

Output:

double_decrement: a union of an already connected pair decrements the count again
component count before the double union: 1
union 0,2 returned false, component count after the double union: 0
the real number of sets: 1
component count after a second double union: -1

The broken union decrements the component count even when both elements already share a set. A correct union returns false in that case and leaves the count alone. This version returns false and decrements anyway, so the count reaches 0 and then -1 while one set still exists. The count is an invariant, and every path out of union must preserve it.

5. A Recursive Find in Python

def find_recursive(parent: list[int], x: int) -> int:
    """Return the root of x, following one parent link per recursive call."""
    if parent[x] == x:
        return x
    return find_recursive(parent, parent[x])


def main() -> None:
    parent = list(range(CHAIN))
    for i in range(CHAIN - 1):
        parent[i] = i + 1
    print(f"recursive find on a {CHAIN}-node chain")

Output, with the traceback summarized:

recursive find on a 10000-node chain
recursion limit 1000, chain depth 9999
Traceback (most recent call last):
  File "pitfalls/recursive_find.py", line 23, in find_recursive
    return find_recursive(parent, parent[x])
  [the same line repeated about 1,000 times]
RecursionError: maximum recursion depth exceeded

The recursive Python find hits the interpreter’s default recursion limit of 1,000 on the 10,000-node chain and raises RecursionError long before it reaches the root. Raising the limit with sys.setrecursionlimit only moves the crash to the C stack under the interpreter. The iterative find in union_find.py avoids both limits. The same rule applies in every language: a recursive find’s stack depth equals the tree depth, so the input must never decide it.

Key Takeaways

  • Union-Find keeps disjoint sets as a forest of parent pointers. find walks to a root, union links two roots, and connected compares roots.
  • A bare forest can become a chain of n nodes, so a single find can cost O(n).
  • Union by rank attaches the shallower tree under the deeper one and keeps every tree’s height at most log2(n).
  • Path compression points every node on a find path at the root, so repeated finds take one hop.
  • On 10,000 elements joined by chain unions, the final finds walked 49,995,000 hops with neither heuristic, 19,997 with compression alone, and 9,999 with rank alone or both.
  • On that chain input, rank alone ends as a star of depth 1. That is a property of the input, not a reason to drop compression.
  • Both heuristics together give O(m alpha(n)) for m operations, effectively constant per operation.
  • Keep the find iterative: a recursive find overflows the stack on a deep tree in C and hits the recursion limit in Python.

Frequently Asked Questions

Conclusion

Union-Find earns its place by doing almost nothing per operation: one parent walk for a find, and two finds and a rank comparison for a union. The heuristics are small, and the measured difference is not. On 10,000 elements joined by chain unions, the bare forest walked 49,995,000 hops in its final finds, while union by rank walked 9,999 and never went deeper than one hop. Compression alone showed why the total and the longest path are different questions: its average fell to 2.00 hops while one first find still paid for all 9,999.

The data structures hub places the forest beside the graph structures. Use union-find whenever connectivity grows incrementally, keep the find iterative, and keep both heuristics rather than assuming one covers for the other.

Source Code and Tests

The programs on this page are in the data-structures/union-find directory of three MYCPLUS example repositories:

LanguageRepository directoryBuild status
Cmycplus/c-examples: data-structures/union-findC union-find build status
C++mycplus/cpp-examples: data-structures/union-findC++ union-find build status
Pythonmycplus/python-examples: data-structures/union-findPython union-find build status

The C and C++ examples build and test with CMake:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

The Python example runs its tests with the standard library:

python3 -m unittest discover -s tests
python3 union_find_demo.py

The demo’s output is compared byte for byte with tests/expected/ordered.txt. The tests compare every operation against a reference model over random unions and finds, check the compression and rank invariants, cover single-element and out-of-range cases, and verify the component count. The C workflow also runs the tests, the demo and the pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer, and the recursive pitfall must report its stack overflow. The Python tests also check the depth table, and the C and C++ experiments are compared with the same captured output.

What I Verified

The example directories contain the test programs and the captured runs. The table states which system ran each check.

CheckUbuntu 24.04 (WSL2)Windows 11
Build and tests, C, GCC 13.3, C11 and C17Pass (4 of 4 tests)Not applicable
Build and tests, C, Clang 18.1.3, C11 and C17Pass (4 of 4 tests)Not applicable
Build and tests, C, MSVC 19.44 /W4 /WXNot applicablePass (4 of 4 tests)
Build and tests, C++, g++ 13.3, C++17 and C++20Pass (4 of 4 tests)Not applicable
Build and tests, C++, clang++ 18.1.3, C++17 and C++20Pass (4 of 4 tests)Not applicable
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive-Not applicablePass (4 of 4 tests, C++17 and C++20)
Python tests and demoPass (26 tests on Python 3.12.3, demo byte-identical)Pass (26 tests on Python 3.14.6, demo byte-identical)
AddressSanitizer and UndefinedBehaviorSanitizer, tests, demo and pitfallsPass (C 4 of 4, C++ 4 of 4)Not applicable
Pitfalls, each caught by the check named in its sectionPass (AddressSanitizer stack overflow, Python RecursionError, 3 output checks)Not applicable
Depth experiment, C, C++ and PythonRun, identical tables, output aboveNot run
Independent rerun on a second Linux x86-64 machine (GCC 13.3, Clang 18.1.3, Python 3.13)Pass (C and C++ 4 of 4 with both compilers, C under ASan and UBSan 4 of 4, Python tests pass, demo and all three depth tables identical to the captures)Not applicable

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, PyPy, and union orders other than the chain used in the depth experiment.

Scroll to Top