AlgoFrames

Disjoint set union: find, union, rank, path compression

Union-find tracks which items are in the same group. Parent arrows point toward a root, and path compression flattens them for near-constant time.

Before you start: Trie applications: autocomplete, word search, XOR maximum.

The idea

Links arrive one at a time: A-B, B-C, D-E. After each link, you must say whether two items are in the same group.

Running a full graph search after every link costs O(n) each time. Union-find answers the same question in nearly constant time.

Intuition

Store each group as a tree of parent arrows. The item at the top, the root, names the group.

Two items are in the same group exactly when their arrows lead to the same root. A root is the one item whose parent is itself.

To merge two groups, point one root at the other. One new arrow joins both whole groups.

Only the root changes. Every item below D still reaches D, and D now leads on to A.

Complexity

Union by size keeps every walk at most log2 n long. Path compression flattens walks further, to amortized O(α(n)) per operation.

α(n) is the inverse Ackermann function. It stays at 4 or less for any n that fits in a computer, so each operation is close to constant.

The structure is two arrays of n entries, parent and size. Space is O(n).

Pitfalls

A new example: union(B, D) that sets parent[B] ← D cuts B and C out of A's set. Always find both roots first and link root to root.

Without the size rule, unions in a bad order build a chain. Then one find walks all n items.

A recursive find on such a chain can also overflow the call stack. The two loops in the code avoid recursion.

Variations

Union by rank keeps an upper bound on each tree's height instead of its size. The lower-rank root goes under the higher one.

Rank gives the same O(log n) height bound. Kruskal's algorithm and many grouping problems use union-find directly.

Code

Pseudocode

parent[i] ← i and size[i] ← 1 for every item; sets ← n
find(x):
  root ← x
  while parent[root] ≠ root: root ← parent[root]
  for each item y on the path from x to root: parent[y] ← root
  return root
union(a, b):
  ra ← find(a), rb ← find(b)
  if ra = rb: return false
  if size[ra] < size[rb]: swap ra and rb
  parent[rb] ← ra; size[ra] ← size[ra] + size[rb]
  sets ← sets − 1; return true

Python

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.sets = n

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while x != root:
            nxt = self.parent[x]
            self.parent[x] = root
            x = nxt
        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.sets -= 1
        return True

JavaScript

class DSU {
  constructor(n) {
    this.parent = Array.from({ length: n }, (_, i) => i);
    this.size = new Array(n).fill(1);
    this.sets = n;
  }
  find(x) {
    let root = x;
    while (this.parent[root] !== root) root = this.parent[root];
    while (x !== root) {
      const next = this.parent[x];
      this.parent[x] = root;
      x = next;
    }
    return root;
  }
  union(a, b) {
    let ra = this.find(a), rb = this.find(b);
    if (ra === rb) return false;
    if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra];
    this.parent[rb] = ra;
    this.size[ra] += this.size[rb];
    this.sets--;
    return true;
  }
}

Java

class DSU {
  int[] parent, size;
  int sets;
  DSU(int n) {
    parent = new int[n];
    size = new int[n];
    for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
    sets = n;
  }
  int find(int x) {
    int root = x;
    while (parent[root] != root) root = parent[root];
    while (x != root) {
      int next = parent[x];
      parent[x] = root;
      x = next;
    }
    return root;
  }
  boolean union(int a, int b) {
    int ra = find(a), rb = find(b);
    if (ra == rb) return false;
    if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
    parent[rb] = ra;
    size[ra] += size[rb];
    sets--;
    return true;
  }
}

Cost at a glance

Accessn/a
Searchfind O(α(n)) amortized
Insertunion O(α(n)) amortized
Deleten/a
SpaceO(n)

Practice problems (6)

Union sequence Warm-up

Six items A to F start in their own sets. Run union(D, A), union(B, E), union(F, C), union(E, A) with union by size. On a tie, union(x, y) puts the root of y under the root of x. Answer each question before the step plays.

Follow the parent arrows Warm-up

The parent array of a union-find is A:A, B:A, C:B, D:B, E:A, F:D. How many parent arrows does find(F) follow before it reaches the root? Answer with a number.

Implement DSU Standard

Complete the class DSU for items 0 to n - 1.

  • find(x) returns the root of x's set.
  • union(a, b) merges the sets of a and b. It returns true when they were in different sets and false when they already shared one.

The given runDsu(n, ops) runs operations "union a b" (result 1 or 0) and "connected a b" (1 when a and b share a set, else 0) and collects the results.

Number of components Standard

An undirected graph has n nodes numbered 0 to n - 1 and a list of edges. Return the number of connected components.

Use union-find: start with n sets and merge the two ends of every edge.

Spot the bug: union without roots Standard

This function should count the connected components of an undirected graph, but it is wrong for some inputs. Click the line with the bug, then fix it.

Implement with union by size and compression Challenge

Build a union-find for items 0 to n - 1 that stays fast on long sequences. runDsu(n, ops) returns one result per operation:

  • "union a b": 1 when two sets merged, 0 when a and b already shared a set
  • "connected a b": 1 when a and b share a set, else 0
  • "size a": the number of items in a's set
  • "count": the number of sets

Use union by size and path compression. The tests include a long chain of unions followed by many finds.

Related topics

Next on the path: Union-find applications: connectivity, grouping, redundant edges