To merge components containing and , make one root point to the other:
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
self.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.