Implement Union-Find
MediumP2Coding
Implement a Union-Find (disjoint set union) over the elements 0 to n - 1. Initially every element is in its own set.
Implement the UnionFind class:
UnionFind(n)createsnsingleton sets.union(x, y)merges the sets containingxandy. Returnstrueif they were in different sets (a merge happened),falseif they were already together.connected(x, y)returnstrueifxandyare in the same set.componentSize(x)returns the number of elements in the set containingx.count()returns the current number of sets.
Use path compression and union by rank (or size) so that operations are near-constant time. The representative chosen for a set is not observable through this interface.
Example 1
- Input
- ["UnionFind","union","union","connected","connected","union","componentSize","count"] [[5],[0,1],[1,2],[0,2],[0,3],[0,2],[2],[]]
- Output
- [null,true,true,true,false,false,3,3]
- Why
- The second union of 0 and 1 changes nothing, so it returns false.
Constraints
- 1 <= n <= 10^5
- 0 <= x, y < n
- At most 2 * 10^5 calls.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 7. ⌘Enter runs, ⌘⇧Enter submits.