DrawCode Algorithm Visualizer • Union-Find • Medium

Union by Rank

Tags: Union-Find, Rank, Amortized, DSU

1. One-Liner

Union by rank always attaches the smaller-height tree under the taller root so the forest stays balanced-ish.


2. The Problem It Solves

Naive union can create linear chains; rank caps approximate height, making find cheaper in practice before path compression.


3. The Core Idea

Maintain rank (upper bound on height). On union, if ranks differ, hang the lower root under the higher; if equal, pick a parent and increment that rank.


4. How It Works (Step-by-Step)

StepAction
1rank[i]=0 initially
2find(x) as basic (iterative)
3For union: compare rank[ra], rank[rb]
4Attach smaller rank under larger; if tie, increment winner's rank

5. Dry Run Example

Both rank 0: union(0,1) → rank of root becomes 1. Another union with rank-0 node attaches under taller root without increasing height unnecessarily.


6. Key Properties

PropertyDetail
RankHeight upper bound, not exact depth with path comp
Tie-breakEither side; consistent rule matters
With path compRank may become outdated but still safe

7. Where It Is Used

Domain / SystemUse
Kruskal MSTStandard DSU
PercolationCluster merging
CompilersUnion-find equivalence classes

8. Interview Tips

Explain why rank helps; contrast with only path compression. Know union by size is similar (count nodes).


9. Comparison with Other Algorithms

TechniqueNotes
Naive unionO(n) skew
Path compression aloneGreat with rank
Link-cut treesMore general dynamic trees

10. Complexity

----
TimeO(α(n)) amortized per op with path compression + rank
SpaceO(n) parent + rank

Implementation Example (PYTHON)

class UnionFind:
    def __init__(self, n):
        self.p = list(range(n))
        self.r = [0] * n

    def find(self, x):
        while self.p[x] != x:
            x = self.p[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.r[ra] < self.r[rb]:
            ra, rb = rb, ra
        self.p[rb] = ra
        if self.r[ra] == self.r[rb]:
            self.r[ra] += 1
        return True

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer