Disjoint Set
Pattern: Disjoint set union
A disjoint-set structure keeps groups that only merge. Each element points to a parent; the root names the group. find follows parents to the root (flattening the path), and union hangs the smaller tree under the larger. Both are almost constant time.
The problem
Build DisjointSet(n) for elements 0 to n - 1, with unionSets(a, b) (merge their groups) and isConnected(a, b)
(are they in the same group?). GFG's version passes a parent array to free functions; this guide uses a class.
Think first
- What does one group look like inside the structure?
- How do you tell whether two elements share a group?
- What keeps the trees short?
Hints
Brute force, and why it fails
Store a group number per element and relabel a whole group on each union: O(n) per union.
The key insight
Trees with path compression and union by size make both operations almost O(1).
Dry run
| groups | {0, 2, 4} {1} {3} |
|---|
DisjointSet(5). unionSets(0, 2), unionSets(4, 2).
The plan
find(x): while parent[x] != x: parent[x] = parent[parent[x]]; x = parent[x]
union: hang the smaller root under the larger
Complexity
- Time
O(α(n)) per operation- Space
O(n)
α is the inverse Ackermann function, below 5 for any real n.
Edge cases
- Union of an element with itself.
- Repeated unions.
- n = 1.
I've built my logic, show the code
Java
class DisjointSet {
private final int[] parent, size;
public DisjointSet(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } // every element is its own group
}
private int find(int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]]; // path halving keeps trees flat
return x;
}
public void unionSets(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return;
if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; } // hang the smaller tree under the bigger
parent[rb] = ra;
size[ra] += size[rb];
}
public boolean isConnected(int a, int b) {
return find(a) == find(b);
}
}C++
class DisjointSet {
public:
vector<int> parent, sz;
DisjointSet(int n) : parent(n), sz(n, 1) {
for (int i = 0; i < n; i++) parent[i] = i; // every element is its own group
}
int find(int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]]; // path halving keeps trees flat
return x;
}
void unionSets(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return;
if (sz[ra] < sz[rb]) swap(ra, rb); // hang the smaller tree under the bigger
parent[rb] = ra;
sz[ra] += sz[rb];
}
bool isConnected(int a, int b) {
return find(a) == find(b);
}
};Python
class DisjointSet:
def __init__(self, n: int):
self.parent = list(range(n)) # every element is its own group
self.size = [1] * n
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving keeps trees flat
x = self.parent[x]
return x
def unionSets(self, a: int, b: int) -> None:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra # hang the smaller tree under the bigger
self.parent[rb] = ra
self.size[ra] += self.size[rb]
def isConnected(self, a: int, b: int) -> bool:
return self.find(a) == self.find(b)Common mistakes
- Comparing parents instead of roots.
- Skipping path compression and union by size on big inputs.