DSA · Pro · Pattern 3 of 9
Union-Find (DSU)
12 problems.
Your progress0%
- 1st Visit
- 0/12
- 2nd Visit
- 0/12
- Revise
- 0/12
About this pattern
A disjoint set union (DSU) maintains a partition of elements into groups and supports two operations: find, which returns the representative of an element's group, and unite, which merges two groups. With path compression and union by size, both run in near-constant amortised time. Reach for it when a problem repeatedly merges items that are connected, equivalent or share an attribute, and then asks whether two items belong together, how many groups remain, or how large a group is. It detects cycles while undirected edges are added and underpins Kruskal's algorithm. Processing queries offline in sorted order often turns a hard problem into a sequence of merges.
struct DSU {
vector<int> parent, sz;
DSU(int n) : parent(n), sz(n, 1) { iota(parent.begin(), parent.end(), 0); }
int find(int x) {
while (x != parent[x]) x = parent[x] = parent[parent[x]]; // path halving
return x;
}
bool unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return false; // already joined
if (sz[a] < sz[b]) swap(a, b);
parent[b] = a; sz[a] += sz[b];
return true;
}
};