awelgorithms

// learn

Union find (disjoint set union)

Union find, also called disjoint set union (DSU), keeps track of items split into groups. It answers two questions fast: which group is this item in (find), and merge these two groups (union). Two items are connected exactly when find returns the same representative for both.

Updated

Each group is a small tree stored in a parent array, with the root as the group's representative. Two tricks keep the trees flat: attach the smaller tree under the larger one, and point every node you visit straight at the root. With both, each operation is close to constant time.

When to use it

The template

parent = list(range(n))             # each item starts as its own group
size = [1] * n

def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]   # path compression (halving)
        x = parent[x]
    return x

def union(a, b):
    ra, rb = find(a), find(b)
    if ra == rb:
        return False                    # same group: edge makes a cycle
    if size[ra] < size[rb]:
        ra, rb = rb, ra
    parent[rb] = ra                     # union by size: small tree under big
    size[ra] += size[rb]
    return True

The variants you will meet

Find and union

Every item starts as its own root. Find follows parent links to the root; union finds both roots and points one at the other. Two items are connected when their roots match.

Union by rank or size

Always hang the shorter (or smaller) tree under the taller (or larger) one, so trees stay O(log n) deep even before path compression.

Path compression

While finding the root, repoint each node you pass closer to it. Later finds on those nodes take one or two steps.

Counting and connectivity

Start with n components and subtract one for every union that merges two different roots. Answer connectivity questions as edges arrive, or offline by sorting the queries first.

Time and space complexity

With path compression and union by rank or size, a sequence of m operations takes O(m · α(n)), where α is the inverse Ackermann function: below 5 for any n you will ever meet, so effectively O(1) each. Space is O(n) for the parent and size arrays.

check which skills you have 10 minutes, free, no account.

All 10 lessons, in order

Common questions

Union find or DFS for connected components?

For a fixed graph, DFS or BFS counts components in O(V + E) and is simpler. Union find wins when edges arrive over time and you need answers in between, or when you must detect a cycle the moment an edge closes one.

What is path compression?

During find, every node on the path to the root is pointed directly (or closer) to the root. Trees get flatter each time you search them, so repeated finds become nearly free.

Union by rank or union by size?

Either works and both give the same complexity. Size is handy when the problem also asks for the size of the largest group; rank (an upper bound on height) uses slightly smaller numbers.

Can union find split a group back apart?

Not efficiently: it only merges. If edges are removed, process the operations in reverse so removals become unions, or use a different structure.

Other guides