awelgorithms

Union merges two sets

Updated

union(x, y) finds both roots and attaches one root under the other. After that write, find of either index returns one representative.

What to focus on

Attach roots, not the raw x and y when they are not roots. Merging two sets is one parent write.

Worked examples

two singletons

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

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

then another pair

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

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

n=2

a = [0, 1], union(0,1)
  1. parent[1]=0

Result: parent=[0,0]

Try it

Write union(parent, x, y). parent is the parent array. x and y are indices to merge. Find both roots and attach one root under the other. Return the updated parent array. union(0, 1) on [0, 1, 2, 3] → parent=[0, 0, 2, 3]. Then union(2, 3) → parent=[0, 0, 2, 2]. [0, 1] → parent=[0, 0].

x and y are live indices in 0..n-1 with n in 2–6. Every parent slot is a valid index.