AlgoViz

Union-find

medium 20 min

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

Chapter mnemonic

Two Union-Find optimizations

Small hill joins tall hill. Trail signs point to the summit.

Which optimization changes signposts along an existing path?

Path compression redirects visited nodes toward the root. Union by rank guides the merge of two trees.

Video lesson · Chapter 1 of 7

Radio crews reconnect

0:00 / 4:39

Union-find in 75 seconds

1:20Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Store one parent per element. parent[i] = i means i is a root. Every group is a tree, and its root is the group's name

Understand it

Start here

Groups with leaders

Quick recap

  • Graphs

    Vertices joined by edges. A connected component is a maximal set of vertices that can all reach each other. Basics in graphs intro.

  • Trees

    A rooted tree has one root and every other node has exactly one parent. That single parent pointer is all union-find stores.

  • Amortised cost

    The average cost per operation over a long sequence, even if a few single operations are slow.

Union-find tracks elements split into disjoint (non-overlapping) sets. Think of teams with leaders. Find asks "who is the leader of x's team?" and union merges two teams under one leader. Two elements are in the same team exactly when they have the same leader. It answers "are these two connected?" while edges keep arriving, which BFS and DFS cannot do cheaply.

The idea

Two operations: find and union

  • find(x)

    Follow parent pointers from x until a node is its own parent. That root names the set. O(α(n))O(\alpha(n)) amortised.

  • union(a, b)

    Find both roots. If they differ, point one root at the other and return True; if they match, return False. O(α(n))O(\alpha(n)) amortised.

  • connected(a, b)

    Just find(a) == find(b). Same root means same set.

  • count

    Start at nn and subtract one on every union that returns True. That is the number of sets, or connected components.

FIND & MERGE
  1. 1FindWho is the boss of a? Of b?
  2. 2CompareSame boss: nothing to do
  3. 3MergeSmaller team joins the bigger one
  4. 4CompressEveryone visited now points at the boss

Find who is the boss, then merge the teams. Skip the middlemen and let the big fish eat the small fish.

Representation

The parent array and the forest

The entire structure is one array: parent[i] is i's parent, and a root points to itself. Read as a picture, the array is a forest: one tree per set, with an arrow from every element up to its parent. The second array, rank, is only consulted at roots.

Before and after union(2, 4)

Element01234
parent before00033
parent after00003
Before: two sets, {0, 1, 2} with root 0 and {3, 4} with root 3. union(2, 4) finds roots 0 and 3 and links root 3 under root 0. Element 4 is untouched: it now reaches the root through 3.

The same sets as a forest

Arrows point from child to parent. Roots 0 and 3 point to themselves, so they have no arrow until the union draws the dotted one.

Operation 1

find with path compression

find with path compression

The recursion climbs to the root, and on the way back every node on the path is re-pointed to it.

Take the chain 4 → 3 → 2 → 1 → 0. The first find(4) walks all four hops and finds root 0. While the recursion unwinds it sets parent[1], parent[2], parent[3] and parent[4] to 0, so the chain becomes a star. Every later find on those nodes is one hop. The heart of it is one line: parent[x] = find(parent[x]).

Python
parent = [0, 0, 1, 2, 3]          # chain 4 -> 3 -> 2 -> 1 -> 0def find(x):    if parent[x] != x:        parent[x] = find(parent[x])   # path compression    return parent[x]print(find(4), parent)            # 0 [0, 0, 0, 0, 0]def find_halving(x):    while parent[x] != x:        parent[x] = parent[parent[x]] # skip every other node        x = parent[x]    return xparent = [0, 0, 1, 2, 3]print(find_halving(4), parent)    # 0 [0, 0, 0, 2, 2]
Recursive compression, plus the iterative path-halving version that avoids Python's recursion limit on long chains.
Edit and run it in your browser

Operation 2

union by rank or by size

union by rank

Only roots are linked. Rank goes up only when two trees of equal rank meet, and only by one.

If you always hang the first root under the second, a bad order of unions builds a chain of height n−1n - 1, and find becomes O(n)O(n). Union by rank hangs the shorter tree under the taller one, where rank is an upper bound on height. Union by size hangs the smaller set under the larger one. Either keeps every tree shallow.

Why rank keeps trees shallow

size(r)≥2 rank(r)since2k+2k=2k+1⟹height≤rank≤log⁡2n\text{size}(r) \ge 2^{\,\text{rank}(r)} \quad\text{since}\quad 2^{k} + 2^{k} = 2^{k+1} \qquad\Longrightarrow\qquad \text{height} \le \text{rank} \le \log_2 n
A root's rank rises from kk to k+1k + 1 only when it absorbs another root of rank kk. By induction each had at least 2k2^k elements, so the merged tree has at least 2k+12^{k+1}. With only nn elements, rank, and so height, cannot exceed log⁡2n\log_2 n.

Rank or size?

Union by rankUnion by size
Storesupper bound on heightnumber of elements in the set
Link rulelower rank under highersmaller set under larger
Growsby 1, only on a tieby the other set's size, every union
Bonusrank fits in a bytethe size of any set for free: size[find(x)]
Guaranteeheight ≤log⁡2n\le \log_2 nheight ≤log⁡2n\le \log_2 n
Pick size when the problem asks for the largest group or the size of x's group.

Complexity

Why it is nearly O(1)

Cost per operation

Versionfindm operations
Naive linkingO(n)O(n) worst caseO(mn)O(mn)
Union by rank onlyO(log⁡n)O(\log n) worst caseO(mlog⁡n)O(m \log n)
Path compression onlyO(log⁡n)O(\log n) amortisedO(mlog⁡n)O(m \log n)
BothO(α(n))O(\alpha(n)) amortisedO(m α(n))O(m \, \alpha(n))
Space is O(n)O(n) for the parent and rank arrays in every version.

The inverse Ackermann function

α(n)=min⁡{ k≥0:A(k,k)≥n },A(4,4)≫1080  ⟹  α(n)≤4 for any n you can store\alpha(n) = \min\{\, k \ge 0 : A(k, k) \ge n \,\}, \qquad A(4, 4) \gg 10^{80} \;\Longrightarrow\; \alpha(n) \le 4 \text{ for any } n \text{ you can store}
The Ackermann function AA grows faster than any tower of exponents, so its inverse α\alpha grows slower than log⁡∗n\log^{*} n. Tarjan proved the O(m α(n))O(m\,\alpha(n)) bound in 1975, and later work showed no pointer-based structure can do better.

Application 1

Cycle detection in undirected graphs

Add the edges one at a time. Before adding (u,v)(u, v), ask whether uu and vv are already connected. If find(u) == find(v), a path between them already exists, and the new edge would close a loop. Otherwise union them and continue. This is exactly the test Kruskal's algorithm uses to reject an edge.

Cycle check, edge by edge

Each edge costs two finds and at most one link, so the whole check is O(E⋅α(V))O(E \cdot \alpha(V)).

A counting view

acyclic  ⟺  E=V−c,where c=number of components\text{acyclic} \iff E = V - c, \qquad \text{where } c = \text{number of components}
Every edge that joins two different sets lowers cc by one. An edge inside one set leaves cc unchanged, and that is precisely the edge that makes a cycle.

Application 2

Connected components and number of provinces

Cities are connected directly or through other cities; a province is a group of cities that can all reach each other, which is a connected component. Start with nn sets and union the two ends of every connection. Each union that returns True merges two provinces into one.

Components by subtraction

components=n−#{unions that returned True}\text{components} = n - \#\{\text{unions that returned True}\}
No second pass is needed: keep a counter inside the structure and decrement it on every successful union.
Python
def count_provinces(is_connected):    n = len(is_connected)    parent = list(range(n))    def find(x):        while parent[x] != x:            parent[x] = parent[parent[x]]            x = parent[x]        return x    count = n    for i in range(n):        for j in range(i + 1, n):            if is_connected[i][j]:                ri, rj = find(i), find(j)                if ri != rj:                    parent[rj] = ri                    count -= 1    return countprint(count_provinces([[1, 1, 0], [1, 1, 0], [0, 0, 1]]))   # 2print(count_provinces([[1, 0, 0], [0, 1, 0], [0, 0, 1]]))   # 3
Number of provinces from an adjacency matrix. Only the upper triangle is read because the matrix is symmetric.
Edit and run it in your browser

Application 3

Redundant connection

A tree on nn nodes had one extra edge added, so the graph has exactly one cycle. Which edge can you remove to get a tree back? Run the cycle check: the first edge whose union returns False is the answer. Because the edges before it formed a forest, it is the edge that appears last among the cycle's edges in the input.

Edges [1, 2], [2, 3], [3, 4], [1, 4], [1, 5]

Edgefind(u)find(v)Verdict
[1, 2]12union, set {1, 2}
[2, 3]13union, set {1, 2, 3}
[3, 4]14union, set {1, 2, 3, 4}
[1, 4]11same root: redundant
[1, 5]never reached
The cycle is 1-2-3-4-1 and [1, 4] is its last edge in input order. The visualizer's Cycle detection method plays this out.

Application 4

Accounts merge: union-find on labels

Each account is a name followed by emails. Two accounts belong to the same person if they share any email, and sharing is transitive. Treat every email as an element. Within one account, union every email with that account's first email. When all accounts are processed, the emails that share a root belong to one person; group them by root, sort them, and attach the name.

Accounts merge

Accounts 1 and 2 never mention each other's first email, but ana@work.io links them, so they merge.

Choosing

Union-find vs DFS/BFS

Reach for union-find when

  • Edges arrive over time and connectivity is asked in between.
  • You only need "same group or not" and the number or size of groups.
  • You are building an MST with Kruskal or detecting the edge that closes a cycle.
  • Elements are labels (emails, accounts) that merge by shared keys.

Use DFS or BFS instead when

  • You need the actual path, the distance, or the order of visits.
  • The graph is directed: union-find cannot see direction.
  • Edges are deleted: union-find cannot split a set.
  • The graph is static and you only need one pass: O(V+E)O(V + E) traversal is simpler.

Which tool?

On a static graph both are effectively linear. Union-find pulls ahead once queries and new edges interleave.

Side by side

Union-findDFS / BFS
Add an edgeO(α(n))O(\alpha(n))rebuild or re-search, O(V+E)O(V + E)
Connected queryO(α(n))O(\alpha(n))O(V+E)O(V + E) per query, or O(1)O(1) after labelling a static graph
Path between two nodesnot availableyes
Directed graphsnoyes
Extra spaceO(V)O(V)O(V+E)O(V + E) adjacency plus O(V)O(V) visited

Wrap-up

The full structure and what to remember

Python
class UnionFind:    def __init__(self, n):        self.parent = list(range(n))        self.rank = [0] * n        self.size = [1] * n        self.count = n    def find(self, x):        if self.parent[x] != x:            self.parent[x] = self.find(self.parent[x])        return self.parent[x]    def union(self, a, b):        ra, rb = self.find(a), self.find(b)        if ra == rb:            return False        if self.rank[ra] < self.rank[rb]:            ra, rb = rb, ra        self.parent[rb] = ra        self.size[ra] += self.size[rb]        if self.rank[ra] == self.rank[rb]:            self.rank[ra] += 1        self.count -= 1        return Trueuf = UnionFind(6)for a, b in [(0, 1), (0, 2), (3, 4), (2, 4)]:    uf.union(a, b)print(uf.count, uf.size[uf.find(4)], uf.union(1, 3))   # 2 5 False
A reusable union-find with path compression, union by rank, a set counter and set sizes.
Edit and run it in your browser

Key points

  • Union-find keeps disjoint sets as trees in one parent array; a root has parent[x] == x and names its set.
  • find follows parents to the root; path compression re-points every visited node at the root.
  • union links root to root, the shorter tree under the taller (rank) or the smaller set under the larger (size).
  • Rank alone bounds height by log₂ n; together with compression, m operations cost O(m α(n)), effectively constant each.
  • union returning False means the two ends were already connected: a cycle in an undirected graph, or a redundant edge.
  • Components = n minus the successful unions, which solves number of provinces and number of islands.
  • Use a dictionary as the parent map to merge labels such as emails in accounts merge.
  • Prefer DFS/BFS for paths, distances, directed graphs or deletions; prefer union-find when edges arrive over time.

Sources