Fundamentals/Union Find | Disjoint Set Union Introductory Problem
← PrevNext →
Implement UnionFind, a disjoint-set data structure over arbitrary integer labels. A label first appears when it is mentioned in any operation; until then it does not exist.
Methods
merge(x, y): merge the sets containing x and y.
find(x): return the representative root of the set containing x.
isSame(x, y): return true if x and y are in the same set.
Examples
Example 1
Input["UnionFind", "merge", "find", "isSame"]
[[], [0, 1], [0], [0, 1]]
Output[null, null, 1, true]
Explanation: After merging 0 and 1, both share root 1, so isSame(0, 1) is true.
Constraints
Labels are integers introduced lazily on first reference.
Operations should be near O(1) amortized using path compression.