Algo-Sim › Advanced Data Structures
Disjoint Set Union (Rank + Path Compression)
Medium · Advanced Data Structures · step through it in Java, Python and C++ on your own input
Union-find in depth: union by rank keeps trees short, path compression flattens every path a find walks, and together each operation is nearly O(1).
Problem
Design a disjoint-set (union-find) structure over the elements 0..n − 1, each starting in its own set. union(a, b) merges the sets holding a and b and reports whether they were separate; find(x) returns the representative (root) of x's set.
Constraints
- 1 ≤ n ≤ 10⁵ and up to 10⁵ operations in typical problems
- With union by rank and path compression, each operation is O(α(n)): effectively constant
Edge cases to test
- Union of two nodes already joined
- Find on a node never unioned
- A long chain before compression
Follow-up questions
- What does α(n) mean?
- The inverse Ackermann function: at most 4 for any input that fits in the universe, so operations are effectively O(1).
- Can you undo unions?
- Use union by rank without path compression and keep a stack of changes to roll back: O(log n) per find.
Solution
Java
class DSU {
private final int[] parent, rank;
DSU(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false;
if (rank[ra] < rank[rb]) { int t = ra; ra = rb; rb = t; }
parent[rb] = ra;
if (rank[ra] == rank[rb]) rank[ra]++;
return true;
}
}Python
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class DSU {
public:
vector<int> parent, rank;
DSU(int n) {
parent = vector<int>(n);
rank = vector<int>(n);
for (int i = 0; i < n; i++)
parent[i] = i;
}
int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
bool unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb)
return false;
if (rank[ra] < rank[rb]) {
int t = ra;
ra = rb;
rb = t;
}
parent[rb] = ra;
if (rank[ra] == rank[rb])
rank[ra]++;
return true;
}
};