Sub topic 11
Union-find: tracking connected groups
This chapter assumes you know Python dictionaries and loops, and have a rough idea of Big-O. It also assumes you have seen graphs from the previous chapters.
The problem it solves
Some problems ask one question again and again: "Are these two items in the same group?" Groups only merge over time and never split. Examples include computers joined by cables, friends who become linked, and pixels that join into regions.
A graph search such as BFS can answer this, but it re-walks the graph on every query. A set per group works for lookups, but merging two sets copies elements. Union-find (also called a disjoint-set structure) supports exactly two operations cheaply:
find(x)returns a representative of the group containingx.union(a, b)merges the groups containingaandb.
Two items are in the same group when find returns the same representative for both.
How it works
Each group is a tree stored in a parent dictionary. The root of a tree is its own parent, and the root is the group's representative. find follows parent links up to the root. union makes one root point at the other.
Two optimizations keep the trees shallow:
- Union by size. Attach the smaller tree under the larger one, so depth stays small.
- Path compression. During
find, point every visited node directly at the root, so later lookups are shorter.
With both, each operation costs nearly O(1) amortized. Formally it is O(α(n)), where α is the inverse Ackermann function and never exceeds 5 for any practical n.
A working implementation
class UnionFind:
def __init__(self, items):
self.parent = {x: x for x in items}
self.size = {x: 1 for x in items}
self.groups = len(self.parent)
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root: # path compression
self.parent[x], x = root, self.parent[x]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.groups -= 1
return True
def connected(self, a, b):
return self.find(a) == self.find(b)
uf = UnionFind("abcdef")
uf.union("a", "b")
uf.union("b", "c")
uf.union("d", "e")
print(uf.connected("a", "c")) # True
print(uf.connected("a", "e")) # False
print(uf.groups) # 3The groups counter gives the number of components in O(1). Recomputing it from scratch would cost O(n).
When to choose it
| Need | Union-find | BFS/DFS on a graph |
|---|---|---|
| Repeated "same group?" queries as links arrive | Nearly O(1) each | O(V + E) each |
| Count of components | O(1) with a counter | One full traversal |
| Find an actual path between nodes | Not supported | Supported |
| Remove a link | Not supported | Remove the edge |
Union-find is a good fit for detecting cycles in an undirected graph. If union returns False for an edge, both ends were already connected, so that edge closes a cycle. It also powers Kruskal's minimum spanning tree algorithm.
Common mistakes
- Skipping both optimizations. Without them, repeated unions can build a long chain, and
finddegrades to O(n). - Using unhashable items as keys in the dictionary version. Convert lists to tuples first, as covered in the hash table chapter.
- Calling
findon an item that was never added. The dictionary version raisesKeyError. - Comparing
parent[a] == parent[b]instead offind(a) == find(b). Parents are only roots after full resolution.
Exercise
A stream delivers friendship pairs, and after each pair you must report the current number of friend groups. Which structure fits, and how do you get the count?
Show answer
Use union-find. Start with one group per person, so the counter equals the number of people. After each pair, call union. If it returns True, two groups merged and the counter drops by one. Each update is nearly O(1), so you never re-traverse the graph.