awelgorithms

Component count drops by one on union

Updated

Start with n. A successful merge (distinct roots) decrements count by 1. A no-op union leaves count. Floor is 1 when n ≥ 1.

What to focus on

Count is not n minus the number of union calls. No-op unions do not drop the count.

Worked examples

successful

a = [0, 1, 2, 3], count=4, union(0,1)
  1. distinct roots
  2. count 4→3

Result: 3 · parent=[0,0,2,3]

no-op

a = [0, 1, 2, 3], parent=[0,0,2,3], count=3, union(0,1)
  1. find both 0
  2. count stays 3

Result: 3 · parent=[0,0,2,3]

one left

a = [0], count=1, union(0,0)
  1. one root
  2. no-op

Result: 1 · parent=[0]

Try it

Write unionCount(parent, count, x, y). parent is the parent array. count is the current number of components. x and y are indices to merge. If the roots differ, attach and return count - 1. If they match, return count unchanged. union(0, 1) on four singletons drops 4 → 3. Repeating that union keeps 3. union(0, 0) on [0] stays 1.

n is 1–6. count starts at n. x and y are live indices.