AlgoFrames

Implement with union by size and compression

Challenge · Write code · about 25 min

Build a union-find for items 0 to n - 1 that stays fast on long sequences. runDsu(n, ops) returns one result per operation:

  • "union a b": 1 when two sets merged, 0 when a and b already shared a set
  • "connected a b": 1 when a and b share a set, else 0
  • "size a": the number of items in a's set
  • "count": the number of sets

Use union by size and path compression. The tests include a long chain of unions followed by many finds.

Example 1

Input:

[5,["union 0 1","union 2 3","size 0","union 1 3","size 2","count","connected 0 3","union 4 4","count"]]

Output:

[1,1,2,1,4,2,1,0,2]

After union 1 3 the set of 0 to 3 has size 4. union 4 4 changes nothing, so 2 sets remain.

Example 2

Input:

[3,["count","size 1","union 2 1","size 1","connected 0 2","count"]]

Output:

[3,1,1,2,0,2]

Constraints

  • 1 ≤ n ≤ 3000
  • 1 ≤ ops.length ≤ 6000
  • 0 ≤ a, b < n
  • A recursive find may overflow the stack on a long chain

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