Union-Find Pattern
Spot problems about merging groups and dynamic connectivity — redundant connections, provinces, accounts merge, Kruskal.
When a problem keeps merging things into groups and asking "are these two in the same group?", reach for Union-Find. It handles each union/find in effectively O(1) and is often shorter than BFS/DFS.
- Count connected components or groups (provinces, friend circles, islands added over time).
- Detect the edge that creates a cycle in an undirected graph (redundant connection).
- Equivalence relationships: same email → same person,
a == bequations, similar strings. - Connectivity that changes as edges are added over time (online queries).
- Kruskal's minimum spanning tree.
The compact template
int[] parent;
int find(int x) { return parent[x] == x ? x : (parent[x] = find(parent[x])); }
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false;
parent[ra] = rb;
return true;
}
// Init: parent = new int[n]; for i: parent[i] = i;parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False
parent[ra] = rb
return Trueconst parent = Array.from({ length: n }, (_, i) => i);
const find = (x: number): number => (parent[x] === x ? x : (parent[x] = find(parent[x])));
const union = (a: number, b: number): boolean => {
const ra = find(a), rb = find(b);
if (ra === rb) return false;
parent[ra] = rb;
return true;
};(Add union by size/rank for guaranteed near-O(1); path compression alone is usually enough in interviews.)
Redundant connection
A tree plus one extra edge. Process edges in order; the first edge whose endpoints are already connected closes the cycle.
int[] findRedundantConnection(int[][] edges) {
parent = new int[edges.length + 1];
for (int i = 0; i < parent.length; i++) parent[i] = i;
for (int[] e : edges) if (!union(e[0], e[1])) return e;
return new int[0];
}def find_redundant_connection(edges):
parent = list(range(len(edges) + 1))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in edges:
ra, rb = find(a), find(b)
if ra == rb:
return [a, b]
parent[ra] = rbfunction findRedundantConnection(edges: [number, number][]): [number, number] | [] {
const parent = Array.from({ length: edges.length + 1 }, (_, i) => i);
const find = (x: number): number => (parent[x] === x ? x : (parent[x] = find(parent[x])));
for (const [a, b] of edges) {
const ra = find(a), rb = find(b);
if (ra === rb) return [a, b];
parent[ra] = rb;
}
return [];
}Mapping non-integer items
When items are strings (emails, variable names) or grid cells, map them to integer ids first: a HashMap<String, Integer>, or r * cols + c for grid cells. Union-Find over a hash map (parent as a dict) also works.
Weighted Union-Find
Store each node's ratio (or offset) to its parent. Evaluate Division: a / b = 2 unions a and b with weight 2; a query a / c is answered if both share a root, by dividing their weights to the root.
- Number of Provincesmedium
- Redundant Connectionmedium
- Graph Valid Treen−1 edges and no cyclemedium
- Number of Connected Components in an Undirected Graphmedium
- Accounts Mergeunion emailsmedium
- Satisfiability of Equality Equationsunion ==, then check !=medium
- Most Stones Removed with Same Row or Columnn − componentsmedium
- Evaluate Divisionweighted DSUmedium
- Number of Islands IIonline unionshard
- Min Cost to Connect All PointsKruskalmedium
- Union-Find = "merge groups" + "same group?" in near-O(1).
unionreturning false means the edge closes a cycle.- Map strings or grid cells to integer ids.
- Prefer it for incremental connectivity and equivalence grouping.