How can a dynamic network of 1,000,000 servers merge clusters and answer "Are Server A and Server B connected?" in virtually $O(1)$ CPU clock cycles—without ever traversing a graph?
1. In 30 Seconds
Union-Find—formally called a Disjoint Set Union (DSU) [a data structure that tracks a collection of non-overlapping sets]—maintains dynamic connected components under two blazingly fast operations: Find (which component leader owns element $x$?) and Union (merge the components containing $x$ and $y$). By combining two optimizations—Path Compression (flattening parent trees during lookups) and Union by Size/Rank (attaching smaller trees beneath larger ones)—DSU achieves $O(\alpha(N))$ amortized time per query, where $\alpha(N) \le 4$ for every input size in the observable universe.
2. The Real-World Analogy: Corporate Mergers & Parent Companies
Imagine tracking corporate ownership across thousands of tech startups.
- Initially, every startup is its own independent parent company (
parent[i] = i). - When Startup A acquires Startup B, B updates its registration to point to A as its parent company (Union).
- Suppose later Startup C buys A, and Startup D buys C. If an auditor asks, "Who is the ultimate parent conglomerate of Startup B?", you trace
B -> A -> C -> D(Find). - Path Compression is like updating B's legal filing right after that audit so B points directly to D—meaning the next time anyone asks about B, it takes one single lookup instead of climbing the corporate ladder!
3. Picture This
Diagram 1: Union by Size + Path Compression in Action
Initial State (5 isolated sets):
parent: [ 0 | 1 | 2 | 3 | 4 ]
size: [ 1 | 1 | 1 | 1 | 1 ]
1. union(0, 1) and union(2, 3):
0 2
| |
1 3
2. union(0, 2) -> Size[0]==2, Size[2]==2. Attach 2 under 0 (Size[0] becomes 4):
0
/ \
1 2
|
3
3. find(3) with PATH COMPRESSION:
Before find(3): 3 -> 2 -> 0 (Depth 2)
After find(3): 3 points DIRECTLY to root 0! (Depth 1)
0
/ | \
1 2 3 <-- Flattened tree! Future find(3) is 1 single memory read!
Walkthrough: Without Union by Size, merging $N$ items in worst-case order creates a skewed linked list of depth $N$, degrading find() to $O(N)$. Pairing Union by Size with Path Compression collapses tree height to $\le 4$ for $N \le 10^{80}$.
Diagram 2: Flat Array Memory Layout (Zero Pointer Chasing)
Indices (Element ID): [ 0 | 1 | 2 | 3 | 4 ]
parent[] array in RAM: [ 0 | 0 | 0 | 0 | 4 ]
size[] array in RAM: [ 4 | 1 | 1 | 1 | 1 ]
Hardware Advantage:
- No Node objects, no 56-byte Python object headers, no heap fragmentation!
- parent[] for N=100,000 integers fits comfortably inside CPU L2/L3 cache.
Walkthrough: Unlike pointer-based trees scattered across RAM, DSU lives inside two contiguous integer arrays (`parent` and `size`), giving the CPU cache-friendly array indexing.
4. How It Actually Works (First Principles & Invariants)
- The Representative Root Invariant: Every disjoint set is represented by a single rooted tree whose root satisfies
parent[root] == root. Two elements $u$ and $v$ belong to the same connected component if and only iffind(u) == find(v). - Union by Size (Preventing Tall Trees): Always attach the root of the smaller component underneath the root of the larger component (
if size[root_u] < size[root_v]: swap). Because a node's depth only increases when its component size at least doubles, tree height can never exceed $\lfloor \log_2 N \rfloor$ even before path compression. - Path Compression (Self-Healing Lookups): During
find(x), every node visited along the path from $x$ to the root rewrites itsparent[node] = root. Iterative two-pass path compression avoids Python recursion limits on initial deep chains before compression flattens them. - Inverse Ackermann Complexity $O(\alpha(N))$: Robert Tarjan proved that combining both heuristics yields amortized time $O(\alpha(N))$, where $\alpha(N)$ grows so absurdly slowly that $\alpha(10^{80}) = 4$.
5. Show Me The Code
Here is a complete, iterative, stack-safe Python implementation of Disjoint Set Union with Path Compression and Union by Size.
# Day 29: Union-Find (Disjoint Set Union) — Iterative Path Compression & Union by Size
class DisjointSetUnion:
"""
Tracks connected components dynamically in O(alpha(N)) amortized time per operation.
Uses iterative path compression so deep chains never hit Python's recursion limit.
"""
def __init__(self, n):
self.parent = list(range(n)) # Every element starts as its own root
self.size = [1] * n # Component size for Union by Size
self.components = n # Total disjoint clusters remaining
def find(self, x):
"""
Finds the representative root of x and flattens the path (Path Compression).
"""
root = x
while root != self.parent[root]:
root = self.parent[root]
# Second pass: point every node along the path directly to root
while x != root:
nxt = self.parent[x]
self.parent[x] = root
x = nxt
return root
def union(self, x, y):
"""
Merges the components containing x and y.
Returns True if a merge happened, False if x and y were already connected.
"""
root_x = self.find(x)
root_y = self.find(y)
if root_x == root_y:
return False # Already in the same component (adding edge creates a cycle!)
# Union by Size: attach smaller tree under larger tree
if self.size[root_x] < self.size[root_y]:
root_x, root_y = root_y, root_x
self.parent[root_y] = root_x
self.size[root_x] += self.size[root_y]
self.components -= 1
return True
def connected(self, x, y):
return self.find(x) == self.find(y)
if __name__ == "__main__":
dsu = DisjointSetUnion(5)
print("Union(0, 1):", dsu.union(0, 1)) # True
print("Union(2, 3):", dsu.union(2, 3)) # True
print("Union(1, 3):", dsu.union(1, 3)) # True (merges {0,1} and {2,3})
print("Union(0, 2):", dsu.union(0, 2)) # False (cycle detected!)
print("Components left:", dsu.components) # 2 ({0,1,2,3} and {4})
6. Dry Run
Tracing DisjointSetUnion(4) through unions and compressed finds:
| Step | Operation | parent Array | size Array | components |
|---|---|---|---|---|
| 1 | Initialize n = 4 | [0, 1, 2, 3] | [1, 1, 1, 1] | 4 |
| 2 | union(0, 1) | [0, 0, 2, 3] | [2, 1, 1, 1] | 3 |
| 3 | union(2, 3) | [0, 0, 2, 2] | [2, 1, 2, 1] | 2 |
| 4 | union(1, 3) (roots 0 & 2) | [0, 0, 0, 2] | [4, 1, 2, 1] | 1 |
| 5 | find(3) (compresses 3 -> 0) | [0, 0, 0, 0] | [4, 1, 2, 1] | 1 |
7. Speed & Memory
Because every tree stays near-flat via Path Compression and Union by Size, both find and union execute in constant-like amortized time.
| Operation | Amortized Time | Worst-Case Single Call | Space Complexity |
|---|---|---|---|
| Find (with Path Compression) | $O(\alpha(N)) \approx O(1)$ | $O(\log N)$ | $O(1)$ auxiliary (iterative) |
| Union (by Size + Compression) | $O(\alpha(N)) \approx O(1)$ | $O(\log N)$ | $O(N)$ total for parent & size |
8. Where You'll See It In Real Life
- Kruskal's Minimum Spanning Tree (MST): Telecom and power-grid planners sort candidate fiber cables by cost and use Union-Find to connect cities without laying redundant circular loops.
- Image Segmentation & Connected Component Labeling: Computer vision pipelines group adjacent pixels of matching color into unified object masks in real time.
- Social Network & Fraud Cluster Detection: Payment systems merge accounts sharing device fingerprints or IP hashes via DSU to detect synthetic fraud rings instantaneously.
9. Traps To Avoid
- Trap 1: Using Union-Find for directed reachability or directed cycle detection.
Fix: DSU models undirected equivalence relations ($A \sim B \iff B \sim A$). Use 3-color DFS or Kahn's algorithm for directed graphs. - Trap 2: Merging raw elements (
parent[y] = x) instead of merging their roots (parent[root_y] = root_x).
Fix: Always callroot_x = find(x)androot_y = find(y)first—otherwise you rip subtrees apart and corrupt your components! - Trap 3: Modifying
size[root_x]even whenroot_x == root_y.
Fix: Always return early whenroot_x == root_yso you don't double-count component sizes or decrementself.componentsfalsely. - Trap 4: Deleting edges from a standard Union-Find structure.
Fix: Path compression is irreversible; if a problem asks to remove edges over time, process queries in reverse order so deletions become edge additions!
10. Practice
- Easy (Number of Provinces): Given an $N \times N$ symmetric friendship matrix, return the total number of friend circles. Hint: Call
dsu.union(i, j)whenevermatrix[i][j] == 1and returndsu.components. - Medium (Redundant Connection): Given an undirected tree with one extra edge added (creating a single cycle), return the edge that creates the cycle. Hint: Iterate edges in order; the first edge where
dsu.union(u, v)returnsFalseis your culprit! - Hard (Accounts Merge): Given user accounts containing a name and multiple emails, merge accounts that share at least one common email. Hint: Map each email to its first seen account ID, union account IDs whenever an email repeats, then group emails by
dsu.find(account_id).
11. TL;DR
- Union-Find (DSU) tracks dynamic undirected connected components using two flat integer arrays:
parentandsize. - Combining Path Compression and Union by Size yields $O(\alpha(N)) \approx O(1)$ amortized time per operation.
- Whenever
union(u, v)seesfind(u) == find(v), adding edge $(u, v)$ creates an undirected cycle.
12. References Consulted
- GeeksforGeeks — Introduction to Disjoint Set Data Structure (Union-Find) — referenced for verification — all content above is original.
- CP-Algorithms — Disjoint Set Union — referenced for verification — all content above is original.
13. Covered Log Update
Already covered: Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort, Hashing & Hash Maps, Binary Tree, Tree Traversals (DFS/BFS), Binary Search Tree, Heap & Priority Queue, Trie, Graph representations, BFS, Depth-First Search (DFS), Topological Sort, Union-Find.