Algorithms Playbook
Data structureTime ≈ O(1)/op · Space O(n)9 min read

Union-find: grouping things and detecting cycles

A tiny structure that answers "are these two connected?" and merges groups, in almost constant time. Parent array, union by size, path compression, and the problems it solves.

In short

Union-find (disjoint set union) keeps items in groups. find(x) returns the group's representative (root); union(a, b) merges two groups. With union by size and path compression both are effectively O(1).

The idea: a forest of parent pointers

Every item points to a parent; a root points to itself. Two items are in the same group exactly when find takes them to the same root. To merge, hang one root under the other.

Union-find: merging sets, spotting cycles
Speed
00112233445566parent[i]: each node's parent (a root is its own parent)

set size (at roots)

01112131415161
0root1root2root3root4root5root6rootsame colour = same set
1parent = list(range(n))
2size = [1] * n
3
4def find(x):
5 while parent[x] != x:
6 parent[x] = parent[parent[x]]
7 x = parent[x]
8 return x
9
10def union(a, b):
11 ra, rb = find(a), find(b)
12 if ra == rb:
13 return False
14 if size[ra] < size[rb]:
15 ra, rb = rb, ra
16 parent[rb] = ra
17 size[ra] += size[rb]
18 return True
7 separate nodes: every node is its own root. Each union will merge two sets.

Variables

n7
Step 1/16· Unions: 0
Watch the (0, 2) step: both already share a root, so that edge would close a cycle. That one check is how union-find detects cycles and counts components.

Why it's so fast

Union by size

  • Always hang the smaller tree under the bigger one
  • Keeps trees shallow: height ≤ log n

Path compression

  • While walking to the root, point nodes closer to it
  • Future finds on those nodes are almost instant

Together they give amortised O(α(n)) per operation, where α is the inverse Ackermann function: below 5 for any input you will ever see. Treat it as constant.

What it's for

ProblemHow union-find helps
Number of connected components / provincesUnion every edge, count the roots at the end
Does adding this edge create a cycle?If both ends already share a root, yes
Redundant connectionThe first edge whose ends are already connected
Kruskal's minimum spanning treeSort edges, add one only if it joins two different sets
Grouping by equivalence (accounts, synonyms)Union the items that are equal

Key takeaways

  • 01find returns the root; two items are connected when their roots match.
  • 02union hangs one root under the other; if the roots match, the edge closes a cycle.
  • 03Union by size + path compression: effectively O(1) per operation.
  • 04Great for components, cycle detection and Kruskal; it cannot undo a union.

Check your understanding

1 of 3

How do you know two nodes are in the same group?

Related topics