Union-Find (Disjoint Set Union)

Track which elements are connected, merging groups in nearly O(1) — with path compression and union by rank.

Intermediate 2 min readLesson 13 of 16 Interview Q&A

Union-Find (also called Disjoint Set Union, DSU) maintains a collection of non-overlapping sets and supports two operations:

  • find(x) — which set is x in? (returns a representative "root")
  • union(x, y) — merge the sets containing x and y.

It answers "are these two things connected?" while connections are being added — far faster than re-running BFS each time.

The idea: a forest of parent pointers

Each set is a tree; each element points to its parent; the root represents the set. Initially everyone is their own root.

2431
Set {1,2,3,4} with root 1. find(4) follows 4 → 3 → 1.

Two optimisations make it extremely fast:

  1. Path compression — during find, point every visited node directly at the root, flattening the tree.
  2. Union by rank / size — attach the shorter (or smaller) tree under the taller one, so trees stay shallow.

With both, any sequence of m operations costs O(m · α(n)), where α is the inverse Ackermann function — at most 4 for any n that fits in the universe. Effectively O(1) per operation.

class DSU {
    private final int[] parent, size;
    private int components;

    DSU(int n) {
        parent = new int[n];
        size = new int[n];
        components = n;
        for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
    }

    int find(int x) {
        if (parent[x] != x) parent[x] = find(parent[x]);   // path compression
        return parent[x];
    }

    boolean union(int a, int b) {
        int ra = find(a), rb = find(b);
        if (ra == rb) return false;                          // already connected
        if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
        parent[rb] = ra;                                     // union by size
        size[ra] += size[rb];
        components--;
        return true;
    }

    boolean connected(int a, int b) { return find(a) == find(b); }
    int count() { return components; }
}

Where Union-Find shines

  • Kruskal's MST — add edges cheapest-first, skipping any that would join an already-connected pair. See MST.
  • Cycle detection in undirected graphs — union returning false means the edge closes a cycle ("Redundant Connection").
  • Number of connected components / provinces as edges arrive.
  • Grouping by equivalence — accounts merge (same email), similar strings, equations a == b.
  • Percolation and image segmentation.
Key takeaways
  • DSU supports find and union over disjoint sets.
  • Path compression + union by rank/size ⇒ amortized near-O(1), technically O(α(n)).
  • Ideal for incremental connectivity, Kruskal, cycle detection and grouping problems.
Interview questions
QWhy does each optimisation alone give O(log n), but both together O(α(n))?hard

Union by rank alone keeps tree height ≤ log n. Path compression alone gives O(log n) amortized. Combined, Tarjan proved the amortized bound O(α(n)) — the inverse Ackermann function, which grows so slowly it is at most 4 for any practical n.

QAccounts merge: merge accounts that share any email.medium

Map each email to an id; for each account, union all its emails with the first one. Then group emails by find(email), sort each group and attach the owner's name. O(n α(n) + sorting).