Graphs Union-find
466. Disjoint Set Union
There are n elements, numbered from 0 to n − 1. At the start, each element is in a set of its own. Write
a class DisjointSet that merges these sets and answers questions about them:
DisjointSet(n)creates thenone-element sets.unionSets(x, y)merges the set that holdsxwith the set that holdsy. It returnstrueif they were two different sets, andfalseifxandywere already in the same set, in which case nothing changes.connected(x, y)returnstrueifxandyare in the same set, andfalseotherwise.setSize(x)returns the number of elements in the set that holdsx.count()returns the number of sets.
Every element is in exactly one set at any time, so the sets never overlap. Each call should take close to constant time on average.
Your class is tested by replaying a list of calls on a new DisjointSet(n). ops[i] names the i-th call:
"unionSets", "connected", "setSize" or "count". args[i] holds its arguments: [x, y] for
unionSets and connected, [x] for setSize, and [] for count. The answer is the list of every value
the calls return, in order.
In C# and Go the methods are UnionSets, Connected, SetSize and Count, and in Rust union_sets,
connected, set_size and count. Go creates the object with Constructor(n), and Rust with
DisjointSet::new(n). The names in ops are the same in every language.
Example 1
Input: n = 5
ops = ["unionSets",
"unionSets",
"connected",
"connected",
"setSize",
"count",
"unionSets",
"setSize",
"count"]
args = [[0, 1],
[3, 4],
[1, 0],
[1, 3],
[4],
[],
[1, 4],
[3],
[]]
[true,true,true,false,2,3,true,4,2]Explanation: The first two merges give the sets {0, 1}, {2} and {3, 4}. So 1 is with 0 but not with 3, the set of 4 has
2 elements, and there are 3 sets. unionSets(1, 4) then merges {0, 1} with {3, 4}, which leaves a set of 4
elements and 2 sets in all.
Example 2
Input: n = 4
ops = ["unionSets",
"unionSets",
"unionSets",
"unionSets",
"connected",
"setSize",
"count"]
args = [[0, 1],
[1, 2],
[2, 0],
[3, 3],
[0, 2],
[1],
[]]
[true,true,false,false,true,3,2]Explanation: After the first two merges, 0, 1 and 2 share one set, so unionSets(2, 0) finds them together and returns
false. unionSets(3, 3) returns false too, because 3 is always in its own set. Neither call changes
anything.
Example 3
Input: n = 1
ops = ["count",
"setSize",
"connected",
"unionSets"]
args = [[], [0], [0, 0], [0, 0]]
[1,1,true,false]Explanation: With one element there is one set, of size 1. An element is always in the same set as itself.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1051 ≤ ops.length ≤ 2 × 105- Each
ops[i]is"unionSets","connected","setSize"or"count". args.lengthequalsops.length, andargs[i]holds two numbers forunionSetsandconnected, one forsetSizeand none forcount.0 ≤ x, y < nfor every argument.
Clarifying questions
What you would ask an interviewer before writing any code.