Skip to the content.

17. Union-Find (Disjoint Set Union)

Back to the index

Track which items belong to the same group while groups merge. With path compression and union by size, each operation is nearly O(1).

How it works

Every item points to a parent; a root points to itself and names its group. find(x) follows parents up to the root. union(a, b) finds both roots and, if different, attaches the smaller tree under the larger one (union by size). During find, every node on the path is re-pointed straight at the root (path compression), so later finds are fast.

If union(a, b) finds the same root for both, the edge a - b would close a cycle. That is how Kruskal’s minimum spanning tree and ‘redundant connection’ problems use it.

Diagram

graph BT
    u0["0"]
    u1["1"]
    u2["2"]
    u3["3"]
    u4["4"]
    u5["5"]
    u1 --> u0
    u2 --> u0
    u3 --> u0
    u5 --> u4

Step-by-step trace

Input: 6 items (0 to 5). Unions in order: (0, 1), (2, 3), (1, 3), (4, 5), (0, 3).

Operation find(a) find(b) Action parent array
start - - every node is its own root [0, 1, 2, 3, 4, 5]
union(0, 1) 0 1 attach root 1 under root 0 [0, 0, 2, 3, 4, 5]
union(2, 3) 2 3 attach root 3 under root 2 [0, 0, 2, 2, 4, 5]
union(1, 3) 0 2 attach root 2 under root 0 [0, 0, 0, 2, 4, 5]
union(4, 5) 4 5 attach root 5 under root 4 [0, 0, 0, 2, 4, 4]
union(0, 3) 0 0 same root: already connected (edge would form a cycle) [0, 0, 0, 0, 4, 4]

Result: Final groups: {0, 1, 2, 3} and {4, 5}. The last union returned False because 0 and 3 were already connected; its find(3) also compressed the path, so 3 now points straight at 0. The diagram shows child –> parent links.

Complexity

Operation Time Space
find / union with both optimizations O(alpha(n)), effectively constant O(n)
find without optimizations (worst) O(n) O(n)

Python reference implementation

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

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:   # path compression
            self.parent[x], x = root, self.parent[x]
        return root

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                # already connected
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra             # union by size: attach smaller under larger
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        return True

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Topological Sort (Kahn’s Algorithm) Next: Minimum Spanning Tree (Kruskal’s Algorithm)