Skip to content
Visual explainer 2h 30m to learn 4 steps

Union-find (disjoint set union)

Implement union-find with path compression and union by rank for near-constant connectivity queries.

By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.

Topic 35 of 54

In short

Union-find, or disjoint set union, tracks which elements belong to the same group as groups merge. find returns a group's representative and union merges two groups. With path compression and union by rank, each operation is nearly constant time.

Explained simply

Imagine a party where people arrive alone and then start forming groups. Every few seconds, someone says "these two people are now in the same group". Now and then, you are asked "are Ana and Ben in the same group?" Union-find is the data structure built for exactly this.

It supports two operations. union(a, b) merges the group of a with the group of b. find(a) returns the leader of a's group, called the representative. Two people are in the same group when their finds return the same leader.

Inside, every element points to a parent, and following parents upward leads to the leader. With two small tricks, path compression and union by rank or size, these chains stay so short that each operation is almost constant time, even for millions of elements.

Union-find is also called disjoint set union, or DSU. Disjoint means the groups never overlap: every element belongs to exactly one group.

Press Play on a diagram to walk through it one step at a time.

MapPath compression flattens the tree
Root r
  • Before: d to c to b to r
    • find(d) walks 3 links
  • After find(d)
    • b points to r
    • c points to r
    • d points to r
FlowThe parent list through four operations (size rule, path halving)
  1. 1
    Start

    parent = [0, 1, 2, 3]: four groups

  2. 2
    union(0, 1)

    parent = [0, 0, 2, 3]: three groups

  3. 3
    union(2, 3)

    parent = [0, 0, 2, 2]: two groups

  4. 4
    union(1, 3)

    Roots 0 and 2 join: [0, 0, 0, 2]

  5. 5
    find(3)

    3 jumps to its grandparent 0: [0, 0, 0, 0]

In depth

The forest inside: parents and roots

Union-find stores a forest, a set of trees, in one list called parent. At the start parent[i] = i: everyone is their own root and their own group. find(x) follows parent links upward until it reaches a root, a node that points to itself. union(a, b) finds both roots and, if they differ, makes one root point to the other. Only roots change during a union.

Without any tricks this can go badly. Union 0 with 1, then 1 with 2, then 2 with 3, always hanging the old tree under the new element, and you get a chain. find(0) now walks the whole chain, O(n) per call, and n operations cost O(n^2).

The two optimisations attack this from both sides. Union by rank or size keeps trees short when they are built. Path compression flattens them whenever find walks through them.

FlowWhat union(a, b) does
  1. 1
    ra = find(a)

    Walk up to a's root

  2. 2
    rb = find(b)

    Walk up to b's root

  3. 3
    Same root?

    Yes: already together, return False

  4. 4
    Pick the bigger tree

    By size or rank

  5. 5
    Link the roots

    Smaller root points to bigger root

Union by rank or by size

Union by size keeps a size count at each root and hangs the smaller tree under the bigger one. Union by rank keeps a rank, an upper bound on the tree's height, and hangs the lower-rank tree under the higher one; the rank grows by one only when two equal ranks are joined.

Either rule guarantees a tree height of at most log2(n). The reason, for size: a node only moves one level deeper when its tree joins one at least as big, so its tree at least doubles each time. A tree cannot double more than log2(n) times. So even without path compression, find is O(log n) in the worst case.

Size has a practical bonus: size[find(x)] tells you how big x's group is, a common question in problems like "largest connected group".

  • Size rule: smaller group goes under the larger
  • Rank rule: lower rank goes under higher; equal ranks add 1
  • Height stays at most log2(n) with either rule

Path compression and the inverse Ackermann bound

Path compression makes every node visited during find point closer to the root. Full compression, usually written recursively, makes every node on the path point straight to the root. Path halving, used in the explainer's code, makes every other node skip to its grandparent in a single loop. Path splitting does the same for every node. All three give the same bound, and halving and splitting need no recursion.

With compression alone, a sequence of operations costs O(log n) amortised per operation. Amortised means averaged over the whole sequence; one single call can still be slow. With compression and union by rank or size together, Tarjan proved the amortised cost is O(alpha(n)), where alpha is the inverse Ackermann function. It grows so slowly that alpha(n) is at most 4 for any n you could ever store, so in practice each operation is constant time.

One honest caveat: compression changes the shape on reads, so a find is not a pure read-only operation, which matters if you share the structure between threads.

Counting components as edges arrive

Keep a counter that starts at n, the number of elements. Every union that joins two different roots lowers it by one. A union of two elements that are already together changes nothing. At any moment the counter is the number of groups, with no extra traversal.

This is where union-find beats BFS and DFS. If the graph is fixed and you ask once, a single DFS in O(V + E) is just as good. But if edges keep arriving and you must answer after each one, rerunning DFS costs O(V + E) per edge, while union-find costs nearly O(1) per edge. Examples: islands appearing on a map one cell at a time, network cables being connected, or Kruskal's algorithm adding edges in order of weight.

The limitation: union-find cannot split groups. Deleting an edge has no cheap operation. Problems with removals are usually solved offline, by processing the events in reverse so removals become additions.

CompareConnectivity: DFS versus union-find
BFS or DFS
  • Graph is fixed
  • One full pass: O(V + E)
  • Can also give paths
  • Must redo work after each new edge
Union-find
  • Edges arrive over time
  • About O(1) per union or find
  • Tracks group count and sizes
  • Cannot remove edges

Variations you will meet

When elements are strings or tuples instead of 0..n-1, use dicts for parent and size and create each element the first time it is seen. This is common in problems like merging accounts that share an email address.

Cycle detection in an undirected graph is one line of logic: process the edges one by one, and if both ends already have the same root, that edge closes a cycle. This is how Kruskal's algorithm skips edges, and how the "redundant connection" problem finds the extra edge in a tree.

Weighted union-find stores, for each node, a value relative to its parent, such as "a is 2 times b". find adds or multiplies these values while compressing the path. It solves problems like evaluating division equations, where you must answer a / c from given ratios a / b and b / c. Always compare roots, find(a) == find(b), never parent[a] == parent[b], since parents are not roots in general.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Implement find and union~40m
  2. 2
    Add path compression~40m
  3. 3
    Add union by rank or size~40m
  4. 4
    Count components dynamically~40m

Key points

  • With both optimisations, operations cost O(alpha(n)), effectively constant.
  • union by rank or size attaches the smaller tree under the larger.
  • Ideal for dynamic connectivity and Kruskal's MST.
  • Adding an edge between two nodes already connected reveals a cycle.

Key terms

Tap a card to flip it. 0/4 known

Examples

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

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

    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a == b: return False
        if self.size[a] < self.size[b]: a, b = b, a
        self.parent[b] = a; self.size[a] += self.size[b]; return True

Finding the redundant edge in a network

A network of n computers was a tree, but one extra cable was added, creating a loop. The cables are given in order and labelled 1..n. Step 1: start with every computer as its own group. Step 2: for each cable (u, v), find both roots. Step 3: if the roots are equal, u and v were already connected, so this cable closes the loop: return it. Otherwise union them. For [[1, 2], [1, 3], [2, 3]], the first two cables join everyone, and [2, 3] is returned. This version links roots without the size rule to stay short; path halving still keeps it fast.

python
def redundant_edge(edges):          # vertices 1..n, n = len(edges)
    parent = list(range(len(edges) + 1))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    for u, v in edges:
        ru, rv = find(u), find(v)
        if ru == rv:
            return [u, v]
        parent[ru] = rv
    return None

Counting friend groups live, with names as keys

A chat app shows how many separate friend groups exist as friendships are added. Step 1: use dicts so any name works, and create a person the first time find sees them, which adds one group. Step 2: each successful union removes one group. Trace: union("ana", "ben") creates two people (count 2) and joins them (count 1). union("cy", "dee") brings it to 3 then 2. union("ben", "dee") joins the two groups: count 1. Each step is nearly O(1).

python
class Groups:                       # works with any hashable keys
    def __init__(self):
        self.parent, self.size, self.count = {}, {}, 0
    def find(self, x):
        if x not in self.parent:
            self.parent[x], self.size[x] = x, 1; self.count += 1
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a == b: return
        if self.size[a] < self.size[b]: a, b = b, a
        self.parent[b] = a; self.size[a] += self.size[b]; self.count -= 1

Quick reference

  • Start: parent = list(range(n)); every element is its own root
  • Same group test: find(a) == find(b), never parent[a] == parent[b]
  • Union by size or rank alone: height at most log2(n), find O(log n)
  • Both optimisations: O(alpha(n)) amortised, alpha(n) <= 4 in practice
  • Group count: start at n, subtract 1 on every successful union
  • Edge whose ends already share a root closes a cycle
  • Union-find cannot split groups; handle removals offline in reverse

Common mistakes

  • Comparing parent[a] with parent[b] instead of find(a) with find(b).
  • Skipping union by size, letting trees become long chains.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1With union by size but no path compression, what is the worst-case cost of find?

Question 2

2You start with 10 elements and perform 6 unions, of which 2 join elements already in the same group. How many groups remain?

Question 3

3Which task is union-find bad at?

Question 4

4What does path compression do during find(x)?

Question 5

5In union by rank, when does a root's rank increase?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    With the explainer's DSU (size rule, path halving) on 5 elements, run union(0, 1), union(2, 3), union(3, 4), union(1, 4). Write the parent list after each step.

  2. Exercise 2medium

    Friendship logs are [time, a, b] for n people. Return the earliest time when everyone is in one group, or -1 if that never happens.

  3. Exercise 3hard

    Given equations like "a==b" and "b!=c" over lowercase letters, return True if all of them can be true at once.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is union-find really O(1)?
Not exactly. With path compression and union by rank or size, it is O(alpha(n)) amortised, and alpha(n) is at most 4 for any realistic n, so it behaves like constant time.
When should I use union-find instead of BFS or DFS?
Use union-find when edges arrive over time and you must answer connectivity questions between additions, or inside Kruskal's algorithm. For a fixed graph and a single question, BFS or DFS is just as fast and can also return paths.
Do I need both path compression and union by rank?
For the best bound, yes. In practice, path compression alone is often fast enough, but adding union by size costs only a few lines and protects against bad input orders.
What is the difference between union by rank and union by size?
Rank tracks an upper bound on tree height, while size tracks the number of elements. Both give the same guarantees; size is often preferred because it also tells you how big each group is.

Go deeper

ShareXLinkedInWhatsApp