Union Find With Path Compression (Python)
Implement a disjoint set union find with path compression and union by rank for near constant amortized time.
Code
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
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `__init__`, `find`, `union` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.