Data Structures19 sections · 729 units
Open in Course

Path Compression

Flattening during find

Path compression makes every node on the find path point directly to the root:

function find(x):
    if this.parent[x] != x:
        this.parent[x] = this.find(this.parent[x])
    return this.parent[x]

After calling find(x), every node from xx to the root now points directly to the root. Future finds on these nodes are O(1)O(1).

Example: chain 12341 \to 2 \to 3 \to 4 (4 is root). After find(1):

  • 141 \to 4
  • 242 \to 4
  • 343 \to 4
  • 444 \to 4 (root)

The tree flattens completely. You see the power of path compression. Even if trees get tall temporarily, find operations flatten them.