Attach the smaller union-find set
Updated
Union by size: compare size[rx] and size[ry]. Attach the smaller set's root under the larger. On a tie, attach either.
What to focus on
Size is member count, not rank. Attach the smaller count even if you are not looking at height.
Worked examples
tie of ones
a = [0, 1, 2, 3], size=[1,1,1,1], union(0,1)- 1=1
- parent[1]=0
- size[0]=2
Result: parent=[0,0,2,3] · size[0]=2
2 vs 1
a = [0, 1, 2, 3], parent=[0,0,2,3], size=[2,1,1,1], union(0,2)- 2>1
- parent[2]=0
Result: parent=[0,0,0,3] · size[0]=3
n=2
a = [0, 1], size=[1,1], union(0,1)- tie
- parent[1]=0
Result: parent=[0,0] · size[0]=2
Try it
Write unionBySize(parent, size, x, y). parent is the parent array. size[i] on a root is that set's member count. x and y are indices to merge. Attach the smaller set's root under the larger. On a tie, attach either. Return parent and size. Two size-1 sets: parent=[0, 0, 2, 3], size[0]=2. Then attach the size-1 root 2 under 0. [0, 1] also attaches 1 under 0.
x and y are live indices. size[i] on a root is that set's member count. n is 2–6.