awelgorithms

Count components with union-find

Updated

Initialize count = n. On each successful union, count -= 1. After all unions, count indices with parent[i] == i. Compression does not create or destroy roots.

What to focus on

Scanning self-parents is enough. Do not count union calls. Two no-op unions leave n unchanged.

Worked examples

chain of merges

a = [0, 1, 2, 3], union(0,1) then union(1,2)
  1. 4→3→2
  2. parent[1]=0, parent[2]=0

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

no unions

a = [0, 1, 2, 3]
  1. four self-parents

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

one component

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

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

Try it

Write count(parent). parent is the parent array after the listed unions. Return how many indices have parent[i] == i. Count self-parents, not the number of union calls. Unions (0, 1) then (1, 2) leave 2 components, parent=[0, 0, 0, 3]. No unions: 4. (0, 1), (2, 3), (0, 2): 1, parent=[0, 0, 0, 2].

n is 4. Union arguments are live indices. Count self-parents, not the number of union calls.