Fundamentals · Hard · Free
What is Union-Find (Disjoint Set)? Connected components use case.
FresherFundamentalsData Structures & Algorithms
Union-Find
Track disjoint sets with parent array + rank/path compression—near O(1) union/find. Connected components, Kruskal MST.
java
class UF {
int[] p, r;
int find(int x) { return p[x] == x ? x : (p[x] = find(p[x])); }
void union(int a, int b) {
a = find(a); b = find(b);
if (a == b) return;
if (r[a] < r[b]) p[a] = b; else { p[b] = a; if (r[a] == r[b]) r[a]++; }
}
}Path compression is the magic—mention it by name.