AlgoViz

Union-find

medium 20 min

Union-find, also called a disjoint set union (DSU), keeps elements split into non-overlapping groups.

See it run

Every element points to a parent, every set is a tree with one root, and find and union keep those trees almost flat.

Operations

Parent array

The old execution example: four elements, three unions and one find, read straight off the parent and rank arrays.

Step 1 of 8

Every element is its own root

parent

  1. 00
  2. 11
  3. 22
  4. 33

rank

  1. 00
  2. 01
  3. 02
  4. 03
sets = 4roots = 0, 1, 2, 3

UnionFind(4) sets parent[i] = i for every index, so each element is a root and a set of one. Every rank is 0 and there are 4 sets. Roots are shown in mint.

Step 1: Every element is its own root

class UnionFind:    def __init__(self, n):        self.parent = list(range(n))   # every element is its own root        self.rank = [0] * n            # upper bound on each tree's height        self.count = n                 # number of disjoint sets    def find(self, x):        if self.parent[x] != x:            self.parent[x] = self.find(self.parent[x])   # path compression        return self.parent[x]    def union(self, a, b):        ra, rb = self.find(a), self.find(b)        if ra == rb:            return False               # already in the same set        if self.rank[ra] < self.rank[rb]:            ra, rb = rb, ra            # make ra the taller root        self.parent[rb] = ra           # hang the shorter tree under it        if self.rank[ra] == self.rank[rb]:            self.rank[ra] += 1         # equal heights: the tree grew by one        self.count -= 1        return True    def connected(self, a, b):        return self.find(a) == self.find(b)uf = UnionFind(4)uf.union(0, 1)        # parent [0, 0, 2, 3]uf.union(2, 3)        # parent [0, 0, 2, 2]uf.union(1, 3)        # parent [0, 0, 0, 2]print(uf.find(3))     # 0, and parent[3] becomes 0print(uf.parent, uf.rank, uf.count)# [0, 0, 0, 0] [2, 0, 1, 0] 1
Time
O(α(n)) amortised
Space
O(n)
storage
two int arrays of size n
root test
parent[x] == x

The parent array is the whole data structure. A root is any i with parent[i] == i, and two elements share a set exactly when they reach the same root.

In the real world

The same union-find doing real jobs. Pick one and step through it.

Six computers, cables added one at a time. Are two machines on the same network, and how many separate networks are there?

Step 1 of 5

Six machines, six networks

0net 01net 12net 23net 34net 45net 5

networks

6

No cables yet. Each computer is its own network, labelled with its root, and count = 6.

Step 1: Six machines, six networks

uf = UnionFind(6)            # the class from the methods abovefor a, b in [(0, 1), (1, 2), (3, 4)]:    uf.union(a, b)print(uf.connected(0, 2), uf.connected(0, 4), uf.count)   # True False 3uf.union(2, 4)print(uf.connected(0, 4), uf.count)                        # True 2

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Comparing parents instead of roots

    critical

    parent[x] is only the next hop. In the parent array [0, 0, 0, 2], elements 1 and 3 have parents 0 and 2 but share root 0, so a parent comparison says they are apart when they are together.

    Wrong
    def connected(a, b):    return parent[a] == parent[b]
    Right
    def connected(a, b):    return find(a) == find(b)
  • Linking the elements instead of their roots

    critical

    Setting parent[a] = b cuts a out of its old tree and leaves the rest of a's set behind under the old root, so the two sets never really merge.

    Wrong
    def union(a, b):    parent[a] = b
    Right
    def union(a, b):    ra, rb = find(a), find(b)    if ra != rb:        parent[rb] = ra
  • Calling find without storing the result

    major

    The recursion reaches the root but nothing is rewritten, so there is no path compression and long chains stay long.

    Wrong
    def find(x):    if parent[x] != x:        return find(parent[x])    return x
    Right
    def find(x):    if parent[x] != x:        parent[x] = find(parent[x])   # store it: this is the compression    return parent[x]
  • Raising the rank on every union

    major

    Rank must grow only when two equal ranks meet. Bumping it every time, or hanging the taller tree under the shorter one, throws away the log n height guarantee.

    Wrong
    parent[rb] = rarank[ra] += 1
    Right
    if rank[ra] < rank[rb]:    ra, rb = rb, raparent[rb] = raif rank[ra] == rank[rb]:    rank[ra] += 1
  • Deep recursion in Python

    minor

    Before the first compression a chain can be thousands of nodes long, and recursive find then hits Python's recursion limit. An iterative find with path halving has the same amortised cost and no recursion.

    Wrong
    def find(x):    if parent[x] != x:        parent[x] = find(parent[x])    return parent[x]          # RecursionError on a 10**5 chain
    Right
    def find(x):    while parent[x] != x:        parent[x] = parent[parent[x]]   # path halving        x = parent[x]    return x
  • Using union-find on directed edges

    major

    Union-find forgets direction. The edges 1 → 2, 1 → 3, 2 → 3 make no directed cycle, yet the third edge joins two nodes that already share a root.

    Wrong
    for u, v in directed_edges:    if not union(u, v):        return True           # wrong for directed graphs
    Right
    # directed graph: DFS with three colours,# or Kahn's topological sort (cycle if not all nodes come out)

Interview tips

  • How to explain it

    • Each set is a tree stored in a parent array; the root names the set.
    • find follows parents to the root and compresses the path; union links the shorter root under the taller one.
    • With both tricks, m operations cost O(m α(n)): effectively constant each. Space O(n).
  • Spot the pattern

    • Groups that only ever merge, never split.
    • "Are these two connected?" asked many times while edges keep arriving.
    • Count components, find the edge that closes a cycle, or merge records that share a key.
  • Memory trick: FIND & MERGE

    • Find: who is the boss? Follow parents to the root.
    • Merge: two teams join under one boss.
    • Skip the middlemen (path compression); big fish eats small fish (union by rank).
  • Union-find or DFS/BFS?

    • Static graph, one pass, or you need the actual path: DFS or BFS.
    • Edges arrive over time with connectivity queries in between: union-find.
    • Directed graphs or deletions: not union-find.