Skip to main content

7.7 Disjoint Set Union-Find, Union by Rank & Path Compression

πŸ“šModule 07 β€’ Graphs & Network TraversalsTopic 7.7⏱️13 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ 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 uu and vv already connected?" takes O(V+E)\mathcal{O}(V + E) 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 O(Ξ±(n))β‰ˆO(1)\mathcal{O}(\alpha(n)) \approx \mathcal{O}(1) effective constant time!


🌳 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 -size negatively).
  • 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 O(n)\mathcal{O}(n) skewed chain just like an unbalanced BST!


⚑ Dual Optimization: Union by Rank + Path Compression​

Pairing two simple rules collapses worst-case chain height completely:

  1. Union by Rank / Size (O(log⁑n)\mathcal{O}(\log n) Guaranteed Tree Height): Always attach the shorter (smaller-rank) tree's root beneath the taller (larger-rank) tree's root. Rank increases by +1+1 only when two strictly equal-rank roots merge, guaranteeing maximum depth β‰€βŒŠlog⁑2nβŒ‹\le \lfloor \log_2 n \rfloor.
  2. Path Compression (Self-Flattening find()): While recursing upward from x to the root representative, overwrite every visited ancestor's parent[] directly to root on unwind! Subsequent find() 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 O(Ξ±(n))\mathcal{O}(\alpha(n)), where Ξ±(n)\alpha(n) is the Inverse Ackermann Function.
  • For every practically conceivable dataset in the universe (n≀1080n \le 10^{80}, exceeding estimated atoms in the observable cosmos!), Ξ±(n)≀4\alpha(n) \le 4 β€” making DSU effectively O(1)\mathcal{O}(1) per operation!
Optimization Modefind(x) Worst Casemm Operations Total Amortized Time
Naive Array Merging (Quick-Find)O(1)\mathcal{O}(1)O(mβ‹…n)\mathcal{O}(m \cdot n)
Naive Parent Tree (No Rank/Compress)O(n)\mathcal{O}(n)O(mβ‹…n)\mathcal{O}(m \cdot n)
Union by Rank / Size OnlyO(log⁑n)\mathcal{O}(\log n)O(mlog⁑n)\mathcal{O}(m \log n)
Path Compression OnlyO(log⁑n)\mathcal{O}(\log n) amortizedO(mlog⁑n)\mathcal{O}(m \log n)
Union by Rank + Path CompressionO(Ξ±(n))\mathcal{O}(\alpha(n)) amortizedO(mβ‹…Ξ±(n))β‰ˆO(m)\mathcal{O}(m \cdot \alpha(n)) \approx \mathcal{O}(m)

🏭 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​

πŸ“Problem Statement: Negative-Size Array Trace & Undirected Cycle Checktheorem

Suppose we initialize a 66-element DSU (0…50 \dots 5) 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:

  1. Trace parent[] right after operations: unite(0, 1), unite(2, 3), unite(4, 5), unite(1, 3), unite(0, 5).
  2. If edge (2, 5) arrives next, does unite(2, 5) merge sets or report a cycle? What is parent[3] after calling find(3)?

Step-by-Step Solution:​

  1. Sequential Array Trace (parent[root] = -size):

    • unite(0, 1): Tie (-1 vs -1), attach 1 under 0 β€…β€ŠβŸΉβ€…β€Š\implies parent = [-2, 0, -1, -1, -1, -1].
    • unite(2, 3): Tie (-1 vs -1), attach 3 under 2 β€…β€ŠβŸΉβ€…β€Š\implies parent = [-2, 0, -2, 2, -1, -1].
    • unite(4, 5): Tie (-1 vs -1), attach 5 under 4 β€…β€ŠβŸΉβ€…β€Š\implies parent = [-2, 0, -2, 2, -2, 4].
    • unite(1, 3): find(1)=0 (size 2), find(3)=2 (size 2). Attach 2 under 0 β€…β€ŠβŸΉβ€…β€Š\implies parent = [-4, 0, 0, 2, -2, 4].
    • unite(0, 5): find(0)=0 (size 4), find(5)=4 (size 2). Smaller root 4 attaches directly under larger root 0 β€…β€ŠβŸΉβ€…β€Š\implies parent = [-6, 0, 0, 2, 0, 4]!
  2. Cycle Check on Edge (2, 5) & Path Compression on find(3):

    • find(2) = 0, find(5) = 0. Since find(2) == find(5), edge (2, 5) closes an undirected cycle and unite(2, 5) rejects with false!
    • Calling find(3) walks 3 -> 2 -> 0 and compresses parent[3] straight to 0 (parent[3] = 0).

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. 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 O(Ξ±(n))\mathcal{O}(\alpha(n)) time! Simply freezing rank as an upper-bound tag preserves the O(Ξ±(n))\mathcal{O}(\alpha(n)) theorem untouched.
  2. Does Union-Find work to detect cycles inside a Directed Graph?
    • NO! Union-Find models undirected symmetric equivalence (u∼vβ€…β€ŠβŸΊβ€…β€Šv∼uu \sim v \iff v \sim u). On a directed acyclic diamond A -> B, A -> C, B -> C, DSU falsely sees find(B) == find(C) == A and screams "Cycle!" even though there is NO cycle! Use 3-Color DFS (GRAY) or Kahn's Topological Sort for directed graphs!
  3. 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 O(log⁑n)\mathcal{O}(\log n)) or Link-Cut Trees.
Common Interview Traps: Architectural Trade-Offs
  • Forgetting rank Equality Increment (rank[rx] == rank[ry]): Only increment rank[rx]++ when two strictly equal ranks join (1 + 1 -> height 2); attaching a smaller-rank tree (rank 1 beneath rank 3) leaves parent rank strictly unchanged at 3!
  • 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 findRoot Return: Writing return findRoot(parent, parent[x]) without assigning parent[x] = ... drops Path Compression completely, degrading performance back to O(log⁑n)\mathcal{O}(\log n)!

πŸš€ 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.

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.