Implement DSU
Standard · Write code · about 15 min
Complete the class DSU for items 0 to n - 1.
find(x)returns the root of x's set.union(a, b)merges the sets of a and b. It returns true when they were in different sets and false when they already shared one.
The given runDsu(n, ops) runs operations "union a b" (result 1 or 0) and "connected a b" (1 when a and b share a set, else 0) and collects the results.
Example 1
Input:
[5,["union 0 1","union 2 3","connected 0 3","union 1 3","connected 0 3","union 0 2"]]
Output:
[1,1,0,1,1,0]
connected 0 3 is 0 before union 1 3 and 1 after it. union 0 2 finds one set and returns 0.
Example 2
Input:
[3,["connected 0 1","union 0 0","union 1 0","connected 0 1"]]
Output:
[0,0,1,1]
union 0 0 joins an item with itself, so nothing merges.
Constraints
- 1 ≤ n ≤ 2000
- 1 ≤ ops.length ≤ 4000
- Each op is "union a b" or "connected a b" with 0 ≤ a, b < n
Learn the idea first: Disjoint set union: find, union, rank, path compression, a visual lesson.
More Disjoint set union: find, union, rank, path compression problems
- Union sequence Warm-up
- Follow the parent arrows Warm-up
- Number of components Standard
- Spot the bug: union without roots Standard
- Implement with union by size and compression Challenge