Data Structures19 sections · 729 units
Open in Course

Basic Union

Merging two components

To merge components containing xx and yy, 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 1,2,3,...,n1, 2, 3, ..., n in order, you get a chain of length nn. Then find takes O(n)O(n) time.

You need two optimizations:

1.1. Path compression: flatten trees during find

2.2. Union by rank/size: keep trees balanced during union

Together, these achieve nearly constant time per operation.