Sixteen people join groups in 31 operations. A plain forest of parent pointers follows 89 pointers to answer them. Two small rules, union by rank and path compression, cut that to 27: less than one pointer per operation.
Pick a strategy and drag the operations. Watch the tallest tree and the four cost bars. Then we build, piece by piece, the three operations, the forest, the two rules, and why the cost per operation stays near one.
You need a little Python and the idea of a tree (nodes joined by parent links). Amortized analysis helps but is not required. We build the rest from zero.
Based on Chapter 21, Data Structures for Disjoint Sets, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: van Emde Boas Trees. Next: Elementary Graph Algorithms.
Illustrative workload: people 0 to 7 merge in pairs, then quads, then one group of eight. Then people 8 to 15 join one at a time, and after each join we look up two random members. A hop is one parent pointer followed.
Chapter 0
See a fresh search pay for the whole network on every question, and meet the structure that remembers
You run a small social network. Friendships arrive one at a time. All day, people ask one question: "Are Ana and Ben in the same friend group?" Same group means a chain of friendships links them, of any length.
The obvious answer is a fresh search. Start at Ana, follow every friendship outward with a breadth-first search (visit all neighbours, then their neighbours), and stop if you reach Ben. It is correct. But it forgets everything after each question, so the next question pays again.
200 people. Drag the number of friendships. Each bar is the average work for one question, over 50 random pairs. The axis is logarithmic.
Illustrative: random friendships between 200 people, seeded. Search work counts people visited plus friendships scanned. Union-find work counts parent pointers followed plus one comparison.
With 300 friendships, the fresh search does about 244 steps per question. The structure of this chapter answers the same question in about 3. And as friendships grow, its cost barely moves.
That structure keeps the people in disjoint sets: groups where no person is in two groups. When a friendship joins two groups, it merges them. When someone asks, it checks if two people sit in the same group. It never stores the chain of friends, only the grouping. People also call it union-find.
The failure. Symptom: a "same group?" check slows down as the network grows. Measure: time 1,000 questions at 10,000 and at 20,000 friendships; if the time doubles, each question scans the network. Fix: keep the groups up to date as friendships arrive, so a question costs a few pointer steps.
Chapter 1
Name each set by one of its members, and define the whole structure with three calls
Six people, numbered 0 to 5, start alone. How do we name a group? Each set picks one member as its representative. Two people are in the same set exactly when their sets have the same representative. Which member it is does not matter, if it stays the same while the set does not change.
The whole structure is three operations:
"Are x and y together?" is then one line: Find(x) == Find(y).
Each box is one set. The warm ring marks its representative. Press Next to run the script one line at a time.
The script: Union(0, 1), Union(2, 3), two questions, Union(0, 3), two more questions.
Look at the last questions. We never joined 0 and 2 directly. Union(0, 1), Union(2, 3) and Union(0, 3) put them together anyway. The structure handles this chain of links for you: if a is with b and b is with c, then a is with c.
Count the cost in a real run. With n people and m operations in total, n of the m are MakeSet calls. At most n − 1 Unions can do anything, because each real merge removes one set. CLRS states every bound in this chapter with these two numbers, n and m.
The failure. Symptom: two people show as separate after a merge that should join them. Measure: print Find for both; if the representatives differ, the code merged the wrong sets. Fix: Union must find both representatives first, then link those, never the two people themselves.
Chapter 2
Keep every set as a list, pay for each head pointer you rewrite, and append the short list to the long one
First idea: keep each set as a linked list whose first node is the representative. Every node keeps a head pointer to the first node, so Find costs one step.
Union appends one list to the other, and every appended node needs a new head pointer: one rewrite each. Now always append the list of x, and run Union(0, 1), Union(0, 2), up to Union(0, n − 1). The list that holds 0 grows by one each time. Call the total head rewrites Unaive and the number of people n.
U-naive equals one plus two, and so on up to n minus one, which equals n times n minus one, over two.
Union number i rewrites i pointers. Add 1, 2, up to n − 1. Pair the first and last terms to get n(n − 1)/2 rewrites for n − 1 unions.
n = 8: 1 + 2 + 3 + 4 + 5 + 6 + 7 = 8 × 7 / 2 = 28 rewrites. n = 1,000: 1,000 × 999 / 2 = 499,500 rewrites.
The fix is the weighted-union heuristic: store each list's length, and append the shorter list to the longer one. Follow one person, x. A rewrite of x means x was in the shorter list, so x's list at least doubles. Call the number of rewrites x suffers k.
Two to the k is at most n, so k is at most log base two of n.
Start with a list of 1 and double it k times: at least 2k people. That cannot pass n, so k is at most log₂ n. All n people together suffer at most n log₂ n rewrites.
n = 64: log₂ 64 = 6, so no person is rewritten more than 6 times, and all 64 together at most 384 times. The naive run on 64 people pays 64 × 63 / 2 = 2,016.
Pick a sequence and drag n. Pink is the naive rule, green the weighted rule, the dashed line the n log₂ n ceiling.
"One list grows" runs Union(0, i) for i = 1 to n − 1. "Equal pairs" merges pairs, then quads, then eights: both rules pay the same there, (n/2) log₂ n.
This is CLRS Theorem 21.1: m operations on n elements take O(m + n log n) time. Charging each rewrite to the person who suffers it is the aggregate method of amortized analysis.
The failure. Symptom: merges slow down as groups grow. Measure: log each appended length; if it keeps growing, you append the big list. Fix: append the shorter list.
Chapter 3
Store each set as a tree in one array, make Union one write, and watch Find pay the depth
Lists make Find cheap and Union expensive. Flip it. Keep each set as a rooted tree. Each node points to its parent, one level up. The root points to itself, and the root is the representative. All the trees together form a disjoint-set forest.
The whole structure is one array of n integers. People are numbers 0 to n − 1, and parent[i] is the parent of i.
Press Next. A purple cell is the parent entry that just changed. A blue path is the walk a Find makes to the warm root.
Groups: Union(0, 1), Union(2, 3), Union(4, 5), Union(1, 3), Find(3), Union(3, 5), Find(5). A chain: Union(1, 0), Union(2, 1), up to Union(7, 6), then Find(0).
Trace the Groups script. After Union(0, 1), Union(2, 3) and Union(4, 5), the array is [0, 0, 2, 2, 4, 4]. Union(1, 3) finds roots 0 and 2 and sets parent[2] = 0: [0, 0, 0, 2, 4, 4]. Find(3) walks 3 → 2 → 0, two hops.
Now the danger. In the chain script, each Union puts the old root under a new person. After 7 unions, person 0 sits at depth 7, and Find(0) follows 7 pointers. With n people a chain has depth n − 1, so one Find costs n − 1 hops.
| Structure | Find | Union after the Finds |
|---|---|---|
| Linked lists, weighted | 1 step | up to n/2 rewrites |
| Plain forest | depth of x, up to n − 1 | 1 write |
The forest looks worse. But the shape of a tree can change, and the next two chapters reshape it.
The failure. Symptom: a recursive Find raises RecursionError. Measure: print the depth of the deepest node; Python stops at 1,000 nested calls by default. Fix: write Find as a loop, then keep trees shallow with Chapters 4 and 5.
Chapter 4
Hang the shorter tree under the taller one, and prove the height never passes log₂ n
Hang a tree of height 10 under a tree of height 3, and the result has height 11. Hang the short tree under the tall one, and the height stays 10.
Union by rank makes that choice every time. Each node keeps a rank: an upper bound on the height of its tree, 0 for a new node. Union compares the ranks of the two roots.
Pick a rule and an order, then drag the unions. Small numbers beside the roots are ranks.
Chain order is Union(1, 0), Union(2, 1), up to Union(15, 14). Pairs, then quads, is the tournament that builds the tallest tree rank allows. Random uses a fixed seed.
Why can the height not run away? A rank grows only when two roots of equal rank r merge. Call the number of nodes in the tree under x size(x).
Size of x is at least two to the x-dot-rank.
A new node has rank 0 and size 1 = 20. Rank r + 1 appears only when two roots of rank r merge, and each brings at least 2r nodes. So size(x) is at least 2r + 2r = 2r+1. The rule holds at every step.
Pairs, then quads, on 16 people: root 0 reaches rank 4 and holds 16 = 24 nodes. A rank-5 root would need at least 25 = 32 nodes, so with 16 people no rank passes 4.
The same count limits how many nodes reach a high rank. Call the number of nodes of rank r Nr.
N-r is at most n over two to the r.
Give each rank-r node its 2r or more nodes. No node goes to two of them, and there are only n. So at most n/2r nodes can have rank r. Set Nr = 1: the highest rank is ⌊log₂ n⌋, and so is the tallest tree.
The 16-person tournament ends with 8 nodes of rank 0, 4 of rank 1, 2 of rank 2, 1 of rank 3 and 1 of rank 4. The ceilings are 16, 8, 4, 2 and 1. For n = 1,000,000, ⌊log₂ n⌋ = 19, so a Find follows at most 19 pointers.
Union by size hangs the smaller tree under the larger. It gives the same height bound, plus each group's size.
The failure. Symptom: depths pass log₂ n even with ranks. Measure: check that every root's tree has at least 2rank nodes. Fix: raise a rank only on a tie, for the root that stays on top.
Chapter 5
Make every node a Find passes point straight at the root, so the next Find is one hop
You ask for directions. Each person on the way says "ask my parent", until you reach the root. On the way back, you tell each of them: "the root is right there, skip the middle." The next person who asks gets there in one step.
That is path compression. Find(x) walks up to the root as before. Then it walks the same path again and sets each node's parent to the root. It changes no rank and no answer, only the shape.
The tree starts as a chain of 8 with root 0 at the top. Pick a node and press Find. Purple nodes had their parent rewritten. Then try the two cheaper variants.
The chain is parent = [0, 0, 1, 2, 3, 4, 5, 6]: node i hangs under node i − 1. A plain forest builds it from unlucky unions; union by rank never would. "Visited" counts the nodes the loop steps through below the root.
Trace Find(7) with full compression. The walk up visits 7, 6, 5, 4, 3, 2, 1 and reaches 0: 7 hops. The walk back sets parent to 0 for each of them. The array becomes [0, 0, 0, 0, 0, 0, 0, 0], and Find(7) again costs 1 hop.
Two variants do it in one pass. Path splitting points every node on the path at its grandparent. Path halving does the same for every other node, and jumps two levels each step. Their code differs in one line:
pythondef find(x): # full compression, two passes root = x while parent[root] != root: root = parent[root] while parent[x] != root: parent[x], x = root, parent[x] return root def find_split(x): # every node to its grandparent while parent[x] != x: nxt = parent[x] parent[x] = parent[nxt] x = nxt # step to the OLD parent return x def find_halve(x): # every other node to its grandparent while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] # step to the NEW parent: skip one return x
On the chain, Find(7) with splitting visits 7 nodes and leaves 7 at depth 4. Halving visits 4 nodes and also leaves 7 at depth 4. Full compression leaves it at depth 1. With union by rank, all three give the same bound (Tarjan and van Leeuwen, 1984).
The failure. Symptom: Find returns the right root but stays slow. Measure: call Find(x) twice and count hops; the second call should cost 1. Fix: the second pass must write parent[x] = root for every node on the path.
Chapter 6
Grow the workload from 16 to 16,384 people and watch only one curve stay flat
Each rule alone helps. Union by rank caps the height at log₂ n. Path compression alone also costs about log n per operation over a long run. Together they do far better. Measure it before we explain it.
Pick a workload and drag n. Both axes are logarithmic. Each line is one strategy; the dots are your n.
Illustrative, seeded runs. "Groups then joiners" is the hero's workload at size n: about 2n operations. "Random" is 4n operations, half unions and half Finds on random people.
At n = 1,024 on the hero's workload, the plain forest pays 106 hops per operation. By rank pays 1.96, compression alone 2.85, and both together 0.97. At 16,384 people the plain forest pays 1,658, rank 2.67, compression 3.93. Both together still pay 0.96.
Why do they help each other? Rank keeps every path short, so each compression has little to rewrite. Compression then moves deep nodes up, so the same short path is not climbed twice. CLRS proves the result with a potential function over the ranks. Call the total number of operations m and the number of elements n.
T of m and n is big O of m times alpha of n.
Charge each of the m operations at most a constant times α(n) steps. Add the charges: that bounds the whole run, T(m, n). Single operations can cost more; the total cannot.
m = 10,000,000 operations on n = 1,000,000 people: α(n) = 4, so the run costs at most a constant times 40,000,000 steps. Union by rank alone allows up to 19 hops per Find, a bound of 190,000,000.
This is CLRS Theorem 21.14. Tarjan proved the bound in 1975. Later work showed that no structure of this kind can beat it in general, so α(n) is the true cost, not a weak analysis.
The failure. Symptom: a union-find with both rules still runs slow. Measure: count total hops over the run and divide by m; above 3 or so, a rule is missing. Fix: check that Union calls the compressing Find, and that ties raise a rank.
Chapter 7
Build a function that outgrows towers of powers, and turn it around to get one that barely moves
What is α(n), and why is it at most 4? It is the inverse of a function that grows faster than any tower of powers. Build that function in levels. Level 0 adds one. Each higher level repeats the level below many times.
Call the level k, the input j, and the function at level k Ak. This is CLRS's version.
A-k of j equals j plus one when k is zero. When k is at least one, it equals A-k-minus-one applied j plus one times, starting from j.
To get Ak(j), start with j. Apply level k − 1 to it, then to the result, j + 1 times in all. Level 1 works out to 2j + 1. Level 2 works out to 2j+1(j + 1) − 1.
A1(1) = A0(A0(1)) = 3. A2(1) = A1(A1(1)) = A1(3) = 7. A3(1) = A2(A2(1)) = A2(7) = 28 × 8 − 1 = 2,047. A4(1) = A3(2,047), which is larger than A2(2,047), itself about 620 digits long.
Now turn it around. Call the number of elements n. The inverse asks how high a level you must climb before Ak(1) reaches n.
Alpha of n equals the smallest k such that A-k of one is at least n.
List A0(1), A1(1), A2(1) and so on: 2, 3, 7, 2,047, and then a giant. Walk down the list until a value is at least n. Its level is α(n).
n = 1,000: 7 is too small, 2,047 is enough, so α(1,000) = 3. n = 1080 is about the number of atoms in the visible universe. 2,047 is too small and A4(1) is enough, so α(n) = 4.
Drag n from 1 to 10100. The bands show the value of α(n). We squeeze the scale so the small bands stay visible.
Band edges from the CLRS definition: α(n) is 0 up to n = 2, 1 at n = 3, 2 from 4 to 7, and 3 from 8 to 2,047. It is 4 from 2,048 up to A4(1).
The failure. Symptom: a write-up says union-find is "O(log* n)" or "O(1)" and the numbers disagree with a friend's. Measure: check which definition each source uses; books shift the levels by one or two. Fix: say "O(m α(n)), and α(n) is at most 4 in practice", which every version agrees on.
Chapter 8
Use two Finds to decide if an edge closes a cycle, and build a minimum spanning tree with them
Five towns need a road network. Each possible road has a cost. You want every town reachable for the least total cost. That network is a minimum spanning tree: it touches every town, has no loop, and has the smallest total weight.
Kruskal's algorithm builds it greedily:
Press Next. Teal is the road under test. Green roads stay, red dashed roads close a cycle. The row below is the parent array.
Roads (u, v, cost): (0, 1, 1), (2, 3, 2), (1, 3, 3), (0, 2, 4), (1, 2, 5), (3, 4, 6), (2, 4, 7). Union-find uses both rules.
Trace it. (0, 1, 1) and (2, 3, 2) join separate towns: keep both. (1, 3, 3) finds roots 0 and 2: keep, and the two pairs merge. (0, 2, 4) and (1, 2, 5) find root 0 on both ends: skip. (3, 4, 6) brings in town 4: keep. Four roads for five towns, total cost 1 + 2 + 3 + 6 = 12. The last road, (2, 4, 7), closes a cycle.
The cost: sorting E roads takes O(E log E). The 2E Finds and at most V − 1 Unions take O(E α(V)) in all. The sort dominates. A search for each road to detect a cycle would cost O(V + E) per road instead.
The same check finds the one extra edge in a graph that should be a tree: the first edge whose two ends already share a root. CLRS 23 proves that the greedy choice gives the minimum.
The failure. Symptom: the "tree" has more than V − 1 edges and its cost is too high. Measure: count the kept edges. Fix: test Find(u) against Find(v) before each Union, and skip on a match.
Chapter 9
Open cells one by one and use two extra nodes to see the moment water gets through
Pour water on a block of porous rock. Does it reach the bottom? Model the rock as a grid of cells, all blocked at first. Open cells at random, one at a time. The grid percolates when open cells link the top row to the bottom row through side-by-side neighbours.
Union-find tracks this live. Each cell is an element. When a cell opens, union it with each open neighbour.
Do not test every top cell against every bottom cell. Add two virtual nodes: one joined to every open top-row cell, one to every open bottom-row cell. The grid percolates when Find(top) equals Find(bottom). That is one comparison.
Open cells, or run until the grid percolates. Blue cells connect to the top. When the top meets the bottom, that cluster turns green. Then run 50 trials.
Random openings, fresh on each run. A cell joins its four side neighbours, not diagonals.
Run it a few times. On a 20 × 20 grid our 400 seeded runs percolated at 59.1% open on average, and most runs fell between 54% and 64%. On 40 × 40 the spread narrows to about 3 points around 59.2%. For huge grids the value settles near 59.27%. Below it, a grid almost never percolates; above it, it almost always does.
Each trial opens about 0.59 N cells for an N-cell grid and does a few Unions per cell. With both rules, a trial costs O(N α(N)): about linear. A search from the top after every opening would cost O(N) each time, O(N2) per trial.
The failure. Symptom: the grid reports "percolates" when no path exists, often because code joined a virtual node to the wrong row. Measure: look for a top or bottom node joined to a cell outside its row. Fix: union a cell with the top node only if it sits in row 0, and with the bottom node only if it sits in the last row.
Chapter 10
Keep the terms, the numbers, the checks and the core code on one page
A disjoint-set structure answers one question: are x and y in the same set? Store each set as a tree in one parent array. Hang the lower-rank root under the higher, and point every node a Find passes at the root. Then m operations on n elements cost O(m α(n)), and α(n) is at most 4 for any n you can store.
| Term | Meaning | Number on this page |
|---|---|---|
| Representative | the member that names a set; the root of its tree | same set exactly when Find(x) == Find(y) |
| Naive list union | always append the list of x | n(n − 1)/2 = 2,016 rewrites for n = 64 |
| Weighted union | append the shorter list | at most log₂ n = 6 rewrites per person for n = 64 |
| Plain forest | second root under the first, no rule | a chain of 8 has depth 7 |
| Union by rank | lower rank under higher; a tie raises one rank | size ≥ 2rank; height ≤ 19 for a million |
| Path compression | every node on the Find path points at the root | Find(7) on the chain: 7 hops, then 1 |
| Both rules | O(m α(n)) total, CLRS Theorem 21.14 | 0.97 hops per operation at n = 1,024 |
| α(n) | smallest k with Ak(1) ≥ n | Ak(1) = 2, 3, 7, 2,047; α(1080) = 4 |
| Kruskal | sorted edges; keep an edge when the roots differ | 4 roads, cost 12 |
| Percolation | top meets bottom through open cells | about 59.3% open on large grids |
pythonclass UnionFind: def __init__(self, n): self.parent = list(range(n)) # MakeSet for 0 .. n-1 self.rank = [0] * n self.count = n # number of sets 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, x, y): rx, ry = self.find(x), self.find(y) if rx == ry: return False # already together: a cycle if self.rank[rx] < self.rank[ry]: rx, ry = ry, rx # union by rank self.parent[ry] = rx if self.rank[rx] == self.rank[ry]: self.rank[rx] += 1 self.count -= 1 return True uf = UnionFind(6) for a, b in [(0, 1), (2, 3), (0, 3)]: uf.union(a, b) print(uf.find(1) == uf.find(2), uf.count) # True 3
| Job | Union-find? |
|---|---|
| Groups that only merge, "same group?" questions | Yes |
| Cycle check in an undirected graph, Kruskal | Yes |
| Merging records that share a key (accounts with one email) | Yes |
| Shortest paths, or the path itself | No: use a search or Dijkstra |
| Directed reachability | No: use a search or strongly connected components |
| Edges that can be deleted | No: it cannot split a set |
Now press Present or Teach. Explain from memory why a rank-r root holds at least 2r nodes, what one compressed Find does to the path, and why α(n) stays at 4. Then go back to the hero, switch from Plain to Both, and say how many pointer hops you saved.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 21, Data Structures for Disjoint Sets (third edition numbering). The definitions of Ak and α follow the book; the devices, the toy workloads and the simulated costs on this page are our own.