Skip to main content
← CONCEPTS / ALGORITHMS & DATA STRUCTURES
An end-to-end domain learning journey

Disjoint Set Union (Union-Find): Path
Compression & Union by Rank.

Disjoint Set Union (DSU) maintains a partition of N elements into non-overlapping sets, supporting find(x) and union(x, y) in O(alpha(N)) amortized time.
Start the journey7 sections· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When concurrent writes contend on shared state, combining Path Compression during find() with Union by Rank/Size during union() bounds tree height so tightly that the inverse Ackermann factor alpha(N) <= 4 for all practical dataset sizes.

TL;DR30-second simplified summary
▾

Storing parent[] and rank[] in contiguous arrays gives excellent CPU cache locality. Iterative path halving avoids recursion limits while achieving the same O(alpha(N)) amortized complexity.

Use negative-size encoding in a single parent[] array when memory bandwidth is tight, and add a rollback stack (without path compression) when edges must be undone.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Amortized Analysis
Amortized Analysis bounds the average cost per operation over any worst-case sequence of n operations—proving why structures with occasional O(n) spikes (dynamic array resizing, Disjoint Set Union, splay trees) still guarantee O(1) or O(alpha(n)) amortized cos...
Full walkthrough · 7 stages
01
STAGE 01 · CORE INTUITIONfoundation

Representing Disjoint Sets as Flat Parent-Pointer Trees.

Why this matters: Represent dynamic connected components as flat parent-pointer arrays for O(1)-ish connectivity checks.

Assume a universe of N elements indexed 0..N-1. Initially every element is its own singleton component: parent[i] = i and rank[i] = 0.

To check whether two nodes belong to the same component, we compare find(a) == find(b). Because each tree has exactly one root (where parent[r] == r), the root ID serves as the canonical component identifier.

STAGE 01 · CORE INTUITION

Representing Disjoint Sets as Flat Parent-Pointer Trees

parent[i] = iInitial Forestfind(a) == find(b)Component Queryunion(a, b)Merge SetsFlat Array LayoutCompact Stateif roots differ

1.Singleton Start: Every element begins as its own root with rank 0 (or negative size -1).

2.Representative Root: Two nodes are connected if and only if they share the same root representative.

3.Memory Efficiency: 200M nodes take only 800 MB in a contiguous int32[] array with zero pointer-chasing objects.

Disjoint Set Union encodes each component as a parent-pointer tree inside a compact contiguous array.

02
STAGE 02 · BALANCED MERGINGfoundation

Preventing Degenerate Chains with Union by Rank & Size.

Why this matters: Prevent O(N) skewed chains during merges by always attaching the smaller-rank tree under the larger-rank root.

When merging roots ra and rb (ra != rb), attaching ra under rb blindly can create a linear chain of depth N. Union by Rank compares rank[ra] and rank[rb], attaching the smaller-rank root under the larger-rank root and incrementing rank only on ties.

Union by Size tracks component cardinality in size[root] (often stored as negative values inside parent[root] to halve memory footprint) and always attaches the smaller component to the larger one.

STAGE 02 · BALANCED MERGING

Preventing Degenerate Chains with Union by Rank & Size

ra = find(a), rb =find(b)Merge InputsCompare rank[ra],rank[rb]Balance RuleIf rank[ra] ==rank[rb]Height BoundMax Depth <=log2(N)Worst-Case Guaranteebreaks ties

1.Why Naive Union Fails: Always attaching ra under rb can build a linked list of depth N, making find() O(N).

2.Union by Rank / Size: Attaching the smaller tree under the larger tree guarantees height never exceeds log2(N).

3.Rank Bump Rule: Tree height only increases by 1 when two equal-rank trees are merged.

Union by Rank attaches the shallower tree under the deeper root, bounding tree height to O(log N).

Engineering Decision Framework
Problem
How to implement Disjoint Set Union (Union-Find): Path Compression & Union by Rank without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When concurrent writes contend on shared state, combining Path Compression during find() with Union by Rank/Size during union() bounds tree height so tightly that the inverse Ackermann factor alpha(N) <= 4 for all practical dataset sizes.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Disjoint Set Union (Union-Find): Path Compression & Union by Rank experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · TREE FLATTENINGintermediate

Collapsing Lookup Paths with Recursive & Iterative Path Compression.

Why this matters: Flatten lookup paths dynamically during find() using iterative path compression or path halving.

During find(x), every node on the path from x to root r belongs to the same set. Full path compression sets parent[node] = r for every node on that path; iterative path halving (parent[x] = parent[parent[x]]) achieves the same O(alpha(N)) amortized bound in a tight non-recursive loop with zero stack-overflow risk.

class DisjointSet:
    def __init__(self, n: int) -> None:
        if n < 0:
            raise ValueError('Element count must be non-negative')
        self.parent = list(range(n))
        self.rank = [0] * n
        self.components = n

def find(self, x: int) -> int:
        if not (0 <= x < len(self.parent)):
            raise IndexError(f'Node {x} out of bounds')
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x
STAGE 03 · TREE FLATTENING

Collapsing Lookup Paths with Recursive & Iterative Path Compression

Walk x -> ... ->rootUpward Scanparent[x] =parent[parent[x]]Iterative Zipparent[node] = rootFull CompressionO(alpha(N))AmortizedFlat Treeor flattens

1.Iterative vs. Recursive: Recursive find() risks stack overflow on 10^6-node graphs; iterative path halving uses O(1) stack.

2.Amortized Speed: Every find() permanently shortens future traversals for all nodes along the path.

3.Size + Rank Combo: Negative-size encoding stores both parent and component size in a single int32 array.

Iterative path compression collapses traversal paths to the root, avoiding stack overflow and speeding future lookups.

04
STAGE 04 · COMPLEXITY ANALYSISintermediate

Why O(alpha(N)) Is Effectively Constant Time in Practice.

Why this matters: Combine Path Compression and Union by Rank to achieve O(M * alpha(N)) amortized complexity.

Assuming both Path Compression and Union by Rank are enabled, a sequence of M operations on N elements takes O(M * alpha(N)) time, where alpha(N) is the inverse Ackermann function. For N <= 2^65536 (far exceeding atoms in the observable universe), alpha(N) <= 4.

Memory overhead is strictly 8 bytes per element (two 32-bit ints) or 4 bytes per element using negative-size encoding in a single int32 array.

STAGE 04 · COMPLEXITY ANALYSIS

Why O(alpha(N)) Is Effectively Constant Time in Practice

Rank + PathCompressOptimal PairingInverse AckermannFor N <= 2^65536Sequential int32[]Hardware Speed10^7 Ops / SecProduction Speedruns on

1.Inverse Ackermann Bound: For every realistic dataset up to 2^65536 elements, alpha(N) is at most 4.

2.Why Both Matter: Union by Rank alone gives O(log N); Path Compression alone gives O(log N) worst-case; together they give O(alpha(N)).

3.L1 Cache Locality: Flat primitive arrays avoid heap allocations and keep hot roots in CPU L1/L2 cache.

Combining Union by Rank with Path Compression yields O(alpha(N)) <= 4 operations per query at any practical scale.

05
STAGE 05 · UNDO & DYNAMIC EDGESadvanced

DSU with Rollback for Offline Edge Deletions.

Why this matters: Support offline edge deletions using Rollback DSU by omitting path compression and logging parent mutations.

Path compression mutates parent pointers destructively, making undo impossible. When you need rollback (e.g., offline dynamic connectivity with a segment tree over time), omit path compression and keep Union by Rank/Size alone (O(log N) per op).

Push (rb, prev_parent_rb, ra, prev_rank_ra) onto an undo stack on every union so rollback() restores exact prior state in O(1) time per undone merge.

STAGE 05 · UNDO & DYNAMIC EDGES

DSU with Rollback for Offline Edge Deletions

Union by Size OnlyReversible TreeUndo StackMutation LogSegment Tree OverTimeOffline Windowrollback(checkpoin…O(log N) Undowalks intervals

1.Why Path Compression Breaks Undo: Mutating arbitrary ancestors destroys the exact structural history needed to revert a single union.

2.O(log N) Trade-Off: Keeping Union by Size without path compression preserves O(log N) find() while enabling O(1) per-union rollback.

3.30-Day Sliding Windows: Alternative for streaming graphs: rebuild daily epoch snapshots and swap atomically.

Rollback DSU omits path compression and pushes parent mutations onto an undo stack to support reversible edge deletions.

06
STAGE 06 · CONCURRENT DSUadvanced

Wait-Free & Sharded Union-Find Under Multi-Threaded Workloads.

Why this matters: Scale multi-threaded graph analytics with Wait-Free Union-Find using 64-bit atomic CAS.

In multi-core graph analytics (assuming 64-bit atomic CAS), Wait-Free Union-Find (Anderson & Woll) encodes (parent, rank) into a single 64-bit word and uses compare_exchange_weak so find() performs CAS-based path halving without locks.

For distributed or high-contention services, partition components or batch edges per shard before merging.

STAGE 06 · CONCURRENT DSU

Wait-Free & Sharded Union-Find Under Multi-Threaded Workloads

64-Bit Packed WordAtomic Unitcompare_exchange_we…Wait-Free FindCanonical RootOrderDeadlock-FreeMulti-CoreThroughputParallel Graphresolves

1.Packed CAS: Packing parent and rank into one 64-bit word lets union() update both atomically without locks.

2.Tie-Breaking Invariant: When ranks match, always attach the smaller/larger node ID deterministically to prevent cycles.

3.Contention Reality: If 99% of edges hit one super-node, shard or pre-filter high-degree hubs before DSU.

64-bit packed CAS words and deterministic tie-breaking enable lock-free concurrent Union-Find across cores.

07
STAGE 07 · PRODUCTION PITFALLSadvanced

When Not to Use Standard DSU: Deletions, Recursion & Dynamic IDs.

Why this matters: Guard against stack overflows, super-node false positives, and unbounded dynamic ID maps in production.

Think of When Not to Use Standard DSU: Deletions, Recursion & Dynamic IDs as the intuition layer for Disjoint Set Union (Union-Find): Path Compression & Union by Rank: Guard against stack overflows, super-node false positives, and unbounded dynamic ID maps in production.

Three classic production bugs hit DSU deployments: (1) recursive find() overflowing the call stack on 10^6-node unflattened inputs—always use iterative path compression or path halving; (2) assuming DSU handles arbitrary edge deletions online—use Link-Cut Trees or offline segment-tree-over-time rollback; (3) unbounded string-to-int mapping tables leaking memory without LRU eviction or epoch compaction.

STAGE 07 · PRODUCTION PITFALLS

When Not to Use Standard DSU: Deletions, Recursion & Dynamic IDs

Stack OverflowCrash GuardSuper-Node CollapseFraud FilterString -> int32 MapMemory GuardAlert max_comp_sizeDrift Guardrailbounded by

1.Super-Node Hazard: Merging all accounts sharing an airport Wi-Fi IP collapses millions of innocent users into one component.

2.Degree Quarantine: Filter or quarantine attributes exceeding a degree threshold before calling union().

3.Giant-Component Alert: Trip an ingestion circuit breaker if max_component_size jumps unexpectedly.

Iterative find(), super-node degree caps, and giant-component alerts prevent crashes and false-positive collapses.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must path compression be disabled when implementing DSU with an O(1) rollback stack?

Recommended Learning Flow