Union-Find
Find the root and flatten the path; hang the small tree under the big.
You repeatedly connect items and ask whether two items are already connected.
Trigger words
redundant connection
number of provinces
accounts merge
edges one by one
already connected?
minimum spanning tree
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # shortcut the path
x = self.parent[x]
return x
def union(self, a, b):
root_a = self.find(a)
root_b = self.find(b)
if root_a == root_b:
return False # already connected
if self.size[root_a] < self.size[root_b]:
root_a, root_b = root_b, root_a
self.parent[root_b] = root_a
self.size[root_a] += self.size[root_b]
return TrueSpot it when
- 'Redundant connection', 'number of provinces', 'accounts merge'.
- Edges arrive one by one.
Remember
- union returns False when the two items were already connected: that edge closes a cycle.
- Path shortcuts plus union by size make each operation almost O(1).
How problems bend it
- Redundant connection: Return the first edge whose union returns False.
- Count components: Start with n components and subtract one for every successful union.
- Minimum spanning tree (Kruskal): Sort edges by weight; keep an edge only when union returns True, and add its weight.

