7.7 Disjoint Set Union-Find, Union by Rank & Path Compression
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy:β
Imagine merging corporate startup teams. Every employee answers only one question: "Who do I directly report to?" Initially every founder leads their own 1-person company (parent[i] = i). When two companies merge, the smaller company attaches under the larger company's CEO (keeping reporting chains shallow), and whenever anyone asks "Who's our ultimate CEO?", everyone on that chain updates their phone contact straight to the top CEO in one jump!
π» Bridging to Computer Science:β
Running BFS or DFS after each new edge arrival to test "Are vertices and already connected?" takes per query. The Disjoint Set Union (DSU / Union-Find) tracks dynamic partitioning across disjoint equivalence classes using a lightweight forest array, answering find() and union() in amortized effective constant time!
πTable of Contents
- π³ Parent Array Representation & The Skew Pathology
- β‘ Dual Optimization: Union by Rank + Path Compression
- π Tarjan's Inverse Ackermann Bound O(alpha(n))
- π Real-World Production Context: Kruskal's MST & Streaming Connectivity
- π Numerical Applications & Worked Examples
- π― Exam & Interview Pitfall Check
- π Navigation & Next Steps
π³ Parent Array Representation & The Skew Pathologyβ
Each set corresponds to an inverted parent-pointer tree stored inside a flat integer array parent[0 .. n-1]:
- A root representative points to itself:
parent[root] == root(or stores-sizenegatively). - Every non-root element stores only its single upward
parent[i].
Without balancing heuristics, merging sets blindly (parent[find(x)] = find(y)) can attach tall trees under tiny 1-node roots repeatedly β producing an skewed chain just like an unbalanced BST!
β‘ Dual Optimization: Union by Rank + Path Compressionβ
Pairing two simple rules collapses worst-case chain height completely:
- Union by Rank / Size ( Guaranteed Tree Height): Always attach the shorter (smaller-rank) tree's root beneath the taller (larger-rank) tree's root. Rank increases by only when two strictly equal-rank roots merge, guaranteeing maximum depth .
- Path Compression (Self-Flattening
find()): While recursing upward fromxto the root representative, overwrite every visited ancestor'sparent[]directly torooton unwind! Subsequentfind()queries become single-hop lookups.
Clean C Implementation (find + unite)β
int findRoot(int parent[], int x) {
if (parent[x] != x)
parent[x] = findRoot(parent, parent[x]); // Path Compression!
return parent[x];
}
bool unionByRank(int parent[], int rank[], int x, int y) {
int rx = findRoot(parent, x);
int ry = findRoot(parent, y);
if (rx == ry) return false; // Already connected -> Cycle!
if (rank[rx] < rank[ry]) {
parent[rx] = ry;
} else if (rank[rx] > rank[ry]) {
parent[ry] = rx;
} else {
parent[ry] = rx;
rank[rx]++;
}
return true;
}
π Tarjan's Inverse Ackermann Bound O(alpha(n))β
Combining both Union by Rank (or Size) and Path Compression gives one of algorithm analysis's tightest amortized bounds:
- Each operation averages , where is the Inverse Ackermann Function.
- For every practically conceivable dataset in the universe (, exceeding estimated atoms in the observable cosmos!), β making DSU effectively per operation!
| Optimization Mode | find(x) Worst Case | Operations Total Amortized Time |
|---|---|---|
| Naive Array Merging (Quick-Find) | ||
| Naive Parent Tree (No Rank/Compress) | ||
| Union by Rank / Size Only | ||
| Path Compression Only | amortized | |
| Union by Rank + Path Compression | amortized |
π Real-World Production Context: Kruskal's MST & Streaming Connectivityβ
Disjoint Set Union in Production Algorithms
Ultra-low overhead array merging handles massive streaming connectivity workloads
Kruskal's Minimum Spanning Tree
Network Cable Layout- Processes sorted edges lightest-first, skipping any edge (u, v) where find(u) == find(v).
- DSU filters cycles cleanly in O(E * alpha(V)) after sorting.
Dynamic Undirected Cycle & Grid Percolation
Real-Time Streaming- Detects edge cycles dynamically as links stream in onlineβzero full-graph BFS needed.
- Powers percolation physics simulations and real-time image segmentation.
Hoshen-Kopelman Image Clustering
Computer Vision / GIS- Merges adjacent foreground pixel equivalence labels across single raster scans.
- Flattens fragmented multi-million-pixel blob IDs linearly.
Type Inference & Compiler Unification
ML / Rust / Haskell- Hindley-Milner type unification groups constrained type variables in equivalence sets.
- Path compression immediately resolves chains of polymorphic type aliases.
π Numerical Applications & Worked Examplesβ
Suppose we initialize a -element DSU () storing negative cluster sizes at roots (parent = [-1, -1, -1, -1, -1, -1]) and execute Union by Size (smaller absolute size attaches under larger; tie breaks cleanly toward the smaller node index) alongside Path Compression:
- Trace
parent[]right after operations:unite(0, 1),unite(2, 3),unite(4, 5),unite(1, 3),unite(0, 5). - If edge
(2, 5)arrives next, doesunite(2, 5)merge sets or report a cycle? What isparent[3]after callingfind(3)?
Step-by-Step Solution:β
-
Sequential Array Trace (
parent[root] = -size):unite(0, 1): Tie (-1vs-1), attach1under0parent = [-2, 0, -1, -1, -1, -1].unite(2, 3): Tie (-1vs-1), attach3under2parent = [-2, 0, -2, 2, -1, -1].unite(4, 5): Tie (-1vs-1), attach5under4parent = [-2, 0, -2, 2, -2, 4].unite(1, 3):find(1)=0(size 2),find(3)=2(size 2). Attach2under0parent = [-4, 0, 0, 2, -2, 4].unite(0, 5):find(0)=0(size 4),find(5)=4(size 2). Smaller root4attaches directly under larger root0parent = [-6, 0, 0, 2, 0, 4]!
-
Cycle Check on Edge
(2, 5)& Path Compression onfind(3):find(2) = 0,find(5) = 0. Sincefind(2) == find(5), edge(2, 5)closes an undirected cycle andunite(2, 5)rejects withfalse!- Calling
find(3)walks3 -> 2 -> 0and compressesparent[3]straight to0(parent[3] = 0).
π― Exam & Interview Pitfall Checkβ
- Why track
rank(an upper bound on height) instead of actual tree height when using Path Compression?- Recomputing exact true tree height after Path Compression flattens random branches costs extra subtree scans, destroying time! Simply freezing
rankas an upper-bound tag preserves the theorem untouched.
- Recomputing exact true tree height after Path Compression flattens random branches costs extra subtree scans, destroying time! Simply freezing
- Does Union-Find work to detect cycles inside a Directed Graph?
- NO! Union-Find models undirected symmetric equivalence (). On a directed acyclic diamond
A -> B, A -> C, B -> C, DSU falsely seesfind(B) == find(C) == Aand screams "Cycle!" even though there is NO cycle! Use 3-Color DFS (GRAY) or Kahn's Topological Sort for directed graphs!
- NO! Union-Find models undirected symmetric equivalence (). On a directed acyclic diamond
- Can you easily split or delete an arbitrary edge cleanly inside standard Union-Find?
- No! Standard path compression permanently erases historical merge topology. Handling dynamic edge deletions requires Rollback DSU (omitting path compression, staying at ) or Link-Cut Trees.
- Forgetting
rankEquality Increment (rank[rx] == rank[ry]): Only incrementrank[rx]++when two strictly equal ranks join (1 + 1 -> height 2); attaching a smaller-rank tree (rank 1beneathrank 3) leaves parent rank strictly unchanged at3! - Applying DSU to Weighted Shortest Paths or Directed Graphs: Union-Find tracks pure undirected connectivity, NOT edge direction or path distances (
dist[u]). - Missing Path Compression Inside
findRootReturn: Writingreturn findRoot(parent, parent[x])without assigningparent[x] = ...drops Path Compression completely, degrading performance back to !
π Navigation & Next Stepsβ
Next, we pair Disjoint Set Union-Find directly with Min-Heaps to construct lowest-cost connected backbones in Topic 7.8 β Minimum Spanning Trees: Kruskal's & Prim's Foundations.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.