Union-find
Union-find (disjoint-set union) keeps a partition of elements into groups. find reports which group an element belongs to; union merges two groups. With path compression and union by rank, both operations are nearly O(1).
Detailed Explanation
Many graph problems ask "are these two nodes already connected?" after a stream of edges. Rebuilding components from scratch is too slow. Union-find stores a parent pointer per element. find(x) walks to the root, the representative of x's set. union(x, y) points one root at the other.
Two optimisations make it fast. Path compression sets every node on a find walk to the root, flattening the tree. Union by rank (or by size) attaches the smaller tree to the larger, keeping the height tiny. Combined, the amortised cost is inverse-Ackermann — constant for any n you will see.
The structure does not store edges. It stores connectivity. You cannot list a node's neighbours. You can count components (number of roots), test connectivity, and add edges. Kruskal's minimum spanning tree is: sort edges by weight, union the ends if find differs, skip if they would form a cycle.
In Python a list of parents works when elements are 0..n-1. A dict of parents works for arbitrary hashable nodes. Rank can be a parallel list or dict. A class with find and union returning a bool ("did we merge?") is the usual wrapper.
Undo is not free. Persistent or rollback union-find exists for offline problems; the basic structure is one-way. Deleting an edge means rebuilding.
Initialise every element as its own parent. Forgetting a node means find must create it or raise; pick one and be consistent.
Code Examples
class UnionFind:
def __init__(self, nodes: list[str]):
self.parent = {n: n for n in nodes}
self.rank = {n: 0 for n in nodes}
def find(self, x: str) -> str:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path compression
x = self.parent[x]
return x
def union(self, a: str, b: str) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
uf = UnionFind(["a", "b", "c"])
print(uf.union("a", "b")) # True
print(uf.find("a") == uf.find("b")) # True
print(uf.union("a", "b")) # False, already connected# Kruskal sketch: add cheapest edges that do not form a cycle.
edges = [("a", "b", 1), ("b", "c", 2), ("a", "c", 4)]
uf = UnionFind(["a", "b", "c"])
mst = []
for u, v, w in sorted(edges, key=lambda e: e[2]):
if uf.union(u, v):
mst.append((u, v, w))
print(mst) # [('a', 'b', 1), ('b', 'c', 2)]Common Gotchas
Comparing nodes instead of roots
`a == b` is not connectivity. Compare `find(a) == find(b)`.
Forgetting to initialise a node
`find` raises `KeyError`. Add it in `union` or pre-register every node.
No path compression and no rank
trees become lists and `find` is O(n). Implement both.
`union` returning bool is the cycle test
`False` means the edge was redundant.