To merge components containing and , make one root point to the other:
function union(x, y):
rootX = this.find(x)
rootY = this.find(y)
if rootX != rootY:
this.parent[rootX] = rootY
After this, find(x) and find(y) return the same root.
Problem: without care, trees can become tall. If you union nodes in order, you get a chain of length . Then find takes time.
You need two optimizations:
Path compression: flatten trees during find
Union by rank/size: keep trees balanced during union
Together, these achieve nearly constant time per operation.