Skip to content
Onsite

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) creates n singleton sets.
  • union(x, y) merges the sets containing x and y. Returns true if they were in different sets (a merge happened), false if they were already together.
  • connected(x, y) returns true if x and y are in the same set.
  • componentSize(x) returns the number of elements in the set containing x.
  • 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

Run checks the 2 visible tests, Submit all 7.