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)
.
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