Video in progress
What is Union-Find (Disjoint Set Union), and what do path compression and union by rank give you?
Union-Find merges elements into groups and answers "are these two in the same group?" in nearly O(1). Path compression flattens the tree, and union by rank keeps it from growing tall; together, the cost per operation is practically constant.
📖 Answer
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) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // halve the path
x = parent[x];
}
return x;
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (rank[ra] < rank[rb]) { int t = ra; ra = rb; rb = t; }
parent[rb] = ra;
if (rank[ra] == rank[rb]) rank[ra]++;
return true;
}
}
Without the optimizations, in the worst case the tree turns into a chain and find becomes O(n). With both, the cost is the inverse Ackermann function α(n), which is below 5 for any realistic n.
Inside find I used iterative "path halving". The classic recursive path compression is also correct, but on a million elements the stack can get deep on the first calls.
Where you need it:
- Kruskal's algorithm: if
unionreturnsfalse, the edge creates a cycle; - counting connected components in an undirected graph;
- merging accounts: combining profiles with the same email or phone into one customer.
Its limitation: it only merges, it doesn't split. If you need to remove an element from a group, you need a different structure.
Sign up to mark studied questions and save your progress.