The question it answers
Elements arrive as 0 … n − 1. Over time you learn facts of the form "these two belong together":
two computers got a cable, two accounts share an e-mail address, two cells of a grid were joined.
At any moment you want to ask whether two elements are (directly or indirectly) in the same group,
and how many groups there are.
A disjoint-set structure (also called union-find) supports exactly this:
find(x): the representative ofx's set, one fixed member that names the whole set.union(a, b): merge the sets containingaandb. Returns false if they were already one set.connected(a, b):find(a) == find(b).
Groups only ever merge. There is no "split", and that restriction is what makes the structure so fast.
A forest in an array
Each set is a tree whose root is the representative. Nothing points down; every element stores only its parent, so the whole forest is a single array:
parent = [0, 0, 0, 2, 4, 4] sets: {0, 1, 2, 3} with root 0, and {4, 5} with root 4
0 4
/ \ |
1 2 5
|
3
A root is its own parent. Initially every element is a root: parent[i] = i, n singleton sets.
find(x)followsparentfromxuntil it reaches a root.union(a, b)finds both roots and, if they differ, makes one root the child of the other.
The lab draws the forest with roots at the back and arrows from child to parent, and the parent array itself as the lane of plinths in front. Watch both change together.
Why the naive version is slow
Suppose union(a, b) always sets parent[find(a)] = find(b). The sequence union(0, 1),
union(1, 2), union(2, 3), … then builds a single chain 0 → 1 → 2 → … → n − 1, and find(0)
walks all n nodes. Repeating such finds costs Θ(n) each, Θ(m · n) for m operations. Two independent
fixes bring it down to almost nothing.
Fix 1: union by rank
Give every root a rank, an upper bound on its tree's height, starting at 0. When merging two roots, hang the one with the smaller rank under the larger. Heights then do not grow at all. Only when both ranks are equal does the merged tree possibly get one level taller, so the new root's rank goes up by one.
union(a, b):
ra = find(a), rb = find(b)
if ra == rb: return false
if rank[ra] < rank[rb]: swap(ra, rb)
parent[rb] = ra
if rank[ra] == rank[rb]: rank[ra] += 1
return true
Tie rule used here: on equal ranks the root of the first argument stays root. Any fixed rule works; fixing one makes the exact parent array reproducible, which the shared fixture checks in all four languages.
Why height stays ≤ log₂ n. A root of rank r has at least 2ʳ elements in its tree. True for r = 0
(one element). A root reaches rank r + 1 only by absorbing another root of rank r, so its tree then
has at least 2ʳ + 2ʳ = 2ʳ⁺¹ elements. Since a tree holds at most n elements, r ≤ log₂ n, and a tree's
height never exceeds its root's rank. So find is O(log n) even without the second fix. The lab's
Union by rank preset shows a rank-1 tree absorbing single elements without growing.
Union by size (hang the smaller set under the larger, ties as you like) gives the same log₂ n height bound and the same overall complexity. Some people prefer it because the size of each set is often useful on its own. This lesson uses rank, the version the classic analysis is written for.
Fix 2: path compression
find has just walked from x to the root; every node on that path could point straight at the
root instead. Doing so costs only a constant factor more now and makes later finds from any of them
one hop:
find(x):
root = x
while parent[root] != root: # pass 1: walk up
root = parent[root]
while parent[x] != root: # pass 2: re-point the path
next = parent[x]
parent[x] = root
x = next
return root
The Path compression preset builds a tree of height 2 and then calls find(3) twice. The first
call walks 3 → 2 → 0 and rewires parent[3] to 0 (one pointer rewrite). The second call takes a
single hop. Note that compression does not update ranks: after compression a rank is only an upper
bound on the height, which is all the analysis needs.
Two well-known one-pass alternatives, path halving (point every other node at its grandparent)
and path splitting (point every node at its grandparent), have the same asymptotic bound and avoid
the second loop. The two-pass version is the easiest to reason about, so it is the one shown here.
The implementations are iterative on purpose: a recursive find is shorter but can hit Python's
recursion limit before the tree is flattened.
How fast is it?
| Version | One find (worst case) |
m operations on n elements |
|---|---|---|
| Naive linking | O(n) | O(m · n) |
| Union by rank only | O(log n) | O(m log n) |
| Path compression only | O(n) for one call | O(m log n) amortized (Tarjan and van Leeuwen) |
| Both | O(log n) for one call | O(m α(n)) amortized (Tarjan, 1975) |
α(n) is the inverse Ackermann function. The Ackermann function grows so explosively that its
inverse is at most 4 for any n that could ever be written down in a computer, so in practice each
operation costs a small constant on average. It is still not literally constant: Fredman and Saks
proved in 1989 that no structure for this problem can beat Θ(α(n)) amortized per operation in their
cell-probe model, so union by rank plus path compression is optimal.
"Amortized" matters: a single find can still take O(log n) steps, but the compression it performs
pays for the later cheap ones. Space is O(n): two integer arrays.
What it is good for
- Connectivity as edges arrive. Process edges one at a time with
union;connectedanswers reachability at any point. The Connectivity queries preset does this. - Counting components. Start with n, subtract one for every
unionthat returns true. - Cycle detection in an undirected graph. An edge whose endpoints are already connected closes
a cycle:
unionreturns false. - Kruskal's minimum spanning tree (next module, M27): take edges from lightest to heaviest and keep
each one whose
unionsucceeds. Union-find is the reason that loop is fast. - Equivalence classes in general: merging duplicate accounts, grouping pixels of the same region, unifying types in a compiler.
What it cannot do: split a set, delete an element, or list a set's members without scanning everything. Deleting edges needs other structures (dynamic connectivity), and an "undo" variant must give up path compression to remain fast.
The teaching implementation
The class keeps parent, rank and a set count. Find, Union and Connected are exactly the
pseudocode above, in the same order in all four languages, so the lab can highlight the matching
lines. The listings are the files the tests run: each language replays one shared fixture of
find / union / connected sequences and checks the return values, the exact parent array
after compression, and the set count; then it runs 300 random operation lists against a naive
reference that stores a component label per element and relabels a whole component on every merge.
The naive version is O(n) per union, but obviously correct, which is what a reference should be.
Language notes
| Language | Notes |
|---|---|
| C# | int[] arrays; the swap is a tuple assignment (ra, rb) = (rb, ra). No disjoint-set type in .NET. |
| Python | Lists; the compression step uses tuple assignment self.parent[x], x = root, self.parent[x], which evaluates the right side before assigning. No standard-library equivalent. |
| Java | int[] arrays and a manual swap. No disjoint-set type in the JDK. |
| C++ | union is a keyword, so the method is unite. Indices are std::size_t; std::iota fills the initial parents. The standard library has none; Boost provides boost::disjoint_sets. |
Common mistakes
- Linking the elements instead of their roots:
parent[b] = amerges onlyb's subtree at best and corrupts the forest at worst. Always linkfind(a)andfind(b). - Comparing
parent[a] == parent[b]to test connectivity. Two elements can share a root without sharing a parent. Comparefind(a) == find(b). - Updating ranks during compression, or incrementing rank on every union rather than only on ties.
- Forgetting the
ra == rbcheck: a node linked to itself is a root, but your set count drops by one for nothing.
Edge cases
union(x, x)returns false and changes nothing.findon a root returns it after one check; no compression happens.- A single element: one set,
find(0) = 0. - Out-of-range elements are a caller error; the lab rejects them, the listings rely on array bounds.
Worked practice
1. Start with 4 singletons and run union(2, 3), union(0, 1), union(3, 1). What is the parent
array?
Answer
union(2, 3): equal ranks, 3 goes under 2, rank[2] = 1. union(0, 1): 1 under 0, rank[0] = 1.
union(3, 1): find(3) = 2, find(1) = 0, ranks are equal (1 and 1), so the first argument's root 2
stays root and 0 goes under it: rank[2] = 2. Parent array [2, 0, 2, 2]. (After find(1) compresses,
it becomes [2, 2, 2, 2]; this is the fixture's equal-rank-tie case.)
2. Why does a rank-r root have at least 2ʳ elements, even after path compression?
Answer
Compression only moves nodes within one tree; it never changes which elements belong to a root's set, and it never changes ranks. The size argument is about set sizes at the moment a rank increases, so it still holds.
3. You add the edges of an undirected graph one by one. How do you detect the first edge that creates a cycle?
Answer
Call union(u, v) for each edge; the first call that returns false joins two nodes that were already
connected, so that edge closes a cycle.
Summary
- Disjoint sets are a forest stored in a parent array; a root is its own parent and names its set.
findwalks to the root;unionlinks two roots;connectedcompares roots.- Union by rank keeps height ≤ log₂ n; path compression flattens the paths that
findwalks. - Together: O(m α(n)) for m operations, effectively constant per operation; O(n) space.
- It only merges. That is enough for connectivity, component counting, cycle detection and Kruskal.