Graph Theory37 sections · 1633 units
Open in Course

Implementation - Find with Compression

Coding the Magic

You use recursion to implement Path Compression neatly.

function find(i):
    if parent[i] == i:
        return i
    parent[i] = find(parent[i])
    return parent[i]

The part parent[i] = find(...) is what flattens the tree.

This runs in O(α(n))O(\alpha(n)) amortized time and uses O(n)O(n) space.