Attach the shorter union-find tree
Updated
Union by rank: compare rank[rx] and rank[ry]. Attach the smaller-rank root under the larger-rank root. On a tie, attach either and then increment the new root's rank.
What to focus on
Shorter means smaller rank. Attaching a rank-0 root under a rank-1 tree leaves the tall rank unchanged.
Worked examples
tie
a = [0, 1, 2, 3], rank=[0,0,0,0], union(0,1)- ranks 0=0
- parent[1]=0
- rank[0] 0→1
Result: parent=[0,0,2,3] · rank[0]=1
unequal
a = [0, 1, 2, 3], parent=[0,0,2,3], rank=[1,0,0,0], union(0,2)- rank 1 > 0
- parent[2]=0
- rank[0] stays 1
Result: parent=[0,0,0,3] · rank[0]=1
attach under taller
a = [0, 1, 2], parent=[0,0,2], rank=[1,0,0], union(2,0)- rank[0]=1 > rank[2]=0
- still parent[2]=0
Result: parent=[0,0,0] · rank[0]=1
Try it
Write unionByRank(parent, rank, x, y). parent is the parent array. rank[i] is an integer >= 0 on each root. x and y are indices to merge. Attach the smaller-rank root under the larger-rank root. On a tie, attach either and increment the new root's rank. Return parent and rank. Tie on [0, 1, 2, 3] attaches 1 under 0 and sets rank[0]=1. Then union(0, 2) attaches the short tree. union(2, 0) still hangs 2 under the taller 0.
x and y are live indices. rank[i] is an integer >= 0 on each root. Every parent slot is valid.