Union Find
Implementation
Basic
Note that there is a path compression in the find function.
The time complexity of one operation in UnionFind with N elements and path compression only is amortized O(logN).
class UnionFind {
vector<int> id;
public:
UnionFind(int n) : id(n) {
iota(begin(id), end(id), 0);
}
int find(int a) {
return id[a] == a ? a : (id[a] = find(id[a]));
}
void connect(int a, int b) {
id[find(a)] = find(b);
}
bool connected(int a, int b) {
return find(a) == find(b);
}
};Get Size of Union
We can use a size array to keep track of the size of each union.
cnt keeps track of the number of unions.
Merge using Rank
The time complexity of one operation in UnionFind with N elements, path compression and union by rank is amortized O(alpha(N)) where alpha(N) is the inverse function of Ackermann function. Note that O(alpha(N)) is even more efficient than O(logN).

Problems
Static Connection
959. Regions Cut By Slashes (Medium) Split into sub-cells
Dynamic Connection
Involves multiple steps to build the connection gradually.
Back in Time
Since Union Find can only BUILD connection gradually, when we see problems that BREAK connection gradually with multiple steps, we can traverse the steps in reverse order so as to BUILD the connections gradually.
Last updated
Was this helpful?