Union Find With Path Compression (Python)

Implement a disjoint set union find with path compression and union by rank for near constant amortized time.

PythonData Integrity

Code

pythonsnippet
28 lines
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n
        self.count = n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.rank[ra] < self.rank[rb]:
            self.parent[ra] = rb
        elif self.rank[ra] > self.rank[rb]:
            self.parent[rb] = ra
        else:
            self.parent[rb] = ra
            self.rank[ra] += 1
        self.count -= 1
        return True

    def connected(self, a, b):
        return self.find(a) == self.find(b)

How it works

Union Find With Path Compression (Python) reduces to the class UnionFind and the functions __init__, find, union and connected.

Repetition is confined to while self.parent[x] != x — the rest of the file is straight-line.

Applying it

The primary signature is def find(self, x)

Import find from the file and call it — the rest of the code is implementation detail.

Statements that matter

elif self.rank[ra] > self.rank[rb]:
    self.parent[rb] = ra
def connected(self, a, b):
    return self.find(a) == self.find(b)
def __init__(self, n):
    self.parent = list(range(n))
    self.rank = [0] * n
    self.count = n

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `__init__`, `find`, `union` at load time.