Union-Find Pattern

Spot problems about merging groups and dynamic connectivity — redundant connections, provinces, accounts merge, Kruskal.

Intermediate 2 min readLesson 15 of 25

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.

When to use this pattern
  • 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 == b equations, 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;

(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];
}

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.

Practice problems
  • 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
Key takeaways
  • Union-Find = "merge groups" + "same group?" in near-O(1).
  • union returning false means the edge closes a cycle.
  • Map strings or grid cells to integer ids.
  • Prefer it for incremental connectivity and equivalence grouping.