Disjoint sets: union by rank and path compression
1 Roads that open one at a time
The graphs lesson drew a city of seven junctions. Now the city is still being built. Its six roads open one at a time: 0–1, 1–2, 2–0, 1–3, 3–4 and 5–6. Between openings, people ask whether they can drive from one junction to another yet.
A BFS answers one question in O(V + E). But a problem can open 10⁵ roads and ask 10⁵ questions in between. A fresh BFS for each is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
The questions need only whether a route exists, not the route. So we keep the junctions in groups, the connected components. A disjoint set union (DSU), also called union-find, keeps these groups with two operations, each close to one step:
- find(x) names the group of x.
- union(a, b) joins the groups of a and b.
2 Every group has a leader
Each group has one member as its leader. Two junctions are connected exactly when they have the same leader. So "can we drive from 4 to 0?" becomes "is find(4) equal to find(0)?"
A member does not store its leader. It stores a parent, another member of its group, the way an employee knows only their manager. The leader is its own parent. find(x) follows parents from x until a member points at itself, as a question goes up the managers to the head of the company.
The parents fit in one array, parent. At the start no road is open, so every junction leads a group of one: parent[i] is i.
Each group is a tree, with arrows from child to parent and the leader at the root. The arrows are not roads. Junction 0 can point at 4 with no road between them. The tree only records who belongs with whom.
union(a, b) finds both leaders and points a's leader at b's. Everyone in a's group still reaches their old leader, and one more step reaches the new one.
3 The city, road by road
Here are the six roads, joined this plain way. A ring marks each leader, and the bold arrow is the one that changed:
Road 2–0 found the same leader at both ends. Its ends were already joined, through 1, so this road closes a cycle. Section 7 comes back to it.
Now the questions. find(4) is 4 straight away. find(0) walks 0, 1, 2, 3, 4, four steps. Both give 4, so we can drive from 4 to 0. find(5) gives 6, so junction 5 is cut off from 0.
It works, but the mainland has become a chain.
4 Short trees: union by rank
A long street shows the trouble. Its roads 0–1, 1–2, 2–3 and so on, opened in that order, build a chain of every junction. With 10⁵ junctions, each find from 0 walks 10⁵ steps, and 10⁵ questions are around 10¹⁰ steps again: TLE.
The chain grew because a's tree always went under b's, even when a's tree was taller. The fix is to put the shorter tree under the taller one. Then the taller tree keeps its height. Each leader keeps its tree's height in a second array, rank, which starts at 0. To join two leaders:
- Different ranks. The leader with the lower rank points at the other. No rank changes.
- Equal ranks. a's leader points at b's, as before, and b's rank goes up by 1.
On road 1–2, leader 1 had rank 1 and leader 2 had rank 0, so 2 went under 1.
Why the trees stay short. A tree of rank r has at least 2ʳ members. A single junction has rank 0 and 1 member. A rank grows to r + 1 only when two trees of rank r join, so the joined tree holds at least 2ʳ + 2ʳ = 2ʳ⁺¹. With n members, the rank is at most log₂ n. At n = 10⁵, no find walks more than 16 steps.
Some code keeps each group's size instead, and points the smaller group at the larger. The bound is the same, and the sizes are there when a problem asks for them.
5 Path compression
Union by rank keeps the trees short. Path compression flattens them further each time we look. A find walks from x up to the leader, and every member it passes has that same leader. So after the walk, we point each of them straight at the leader.
Here is find(0) on the mainland's plain chain:
After one long walk, a find from any of 0, 1, 2 or 3 takes one step. In code, find has two loops. The first walks up to the leader. The second walks the same path again and points each member at the leader.
Compression lowers a tree but leaves its rank alone. A rank then becomes an upper bound on the height, and union by rank still works.
Both together. A run of m operations on n members takes about m × α(n) steps. α is the inverse Ackermann function, and it is below 5 for any input you will meet. So each operation costs about one step. The two arrays take O(n) space.
| Version | One find | 10⁵ operations, n = 10⁵ |
|---|---|---|
| Plain union | up to n steps | around 10¹⁰, TLE |
| Union by rank | at most log₂ n, 16 steps | around 2 × 10⁶ |
| Rank and compression | below 5 on average | a few times 10⁵ |
6 The union-find class
The class holds parent and rank. find has the two loops from the steps. unite returns whether it joined two groups, because the next section needs that.
On the city's six roads, unite returns true, true, false, true, true and true. Afterwards, parent is [1, 1, 1, 1, 1, 6, 6]: the leaders are 1 and 6.
C++
union is taken. It is a C++ keyword, so the method is unite. The other tabs use the same name.
new int[n] is all zeros. That is right for rank but not for parent, so the constructor fills parent[i] with i.
No recursion. A recursive find on a chain of 10⁵ passes Python's limit of about 1,000 nested calls and stops with a RecursionError. The two loops never go deep.
Two ways to fill. Array.from({ length: n }, (_, i) => i) gives 0 to n − 1 for parent. new Array(n).fill(0) gives the ranks.
A pointer receiver. The methods take *UnionFind, so find changes the caller's slices. A plain UnionFind receiver would get a copy of the struct.
&mut self even in find. Path compression writes to parent, so find needs &mut self. Indexes are usize, so the edges' i32 values are converted first.
new int[n] is all zeros. That is right for rank but not for parent, so the constructor fills parent[i] with i.
7 Cycles and the number of groups
When unite returns false, both ends already had the same leader. That one result answers two questions:
- A cycle. The ends were already joined by a route. That route and the new road make a cycle.
- The number of groups. Each true joins two groups into one. We start with n groups and take away 1 for each true.
Here is the city with union by rank:
| Road | find(a) | find(b) | unite | Groups |
|---|---|---|---|---|
| start | 7 | |||
| 0–1 | 0 | 1 | true: 0 points at 1 | 6 |
| 1–2 | 1 | 2 | true: 2 points at 1 | 5 |
| 2–0 | 1 | 1 | false: a cycle | 5 |
| 1–3 | 1 | 3 | true: 3 points at 1 | 4 |
| 3–4 | 1 | 4 | true: 4 points at 1 | 3 |
| 5–6 | 5 | 6 | true: 5 points at 6 | 2 |
The count ends at 2, the mainland and the island, as BFS found. Road 2–0 closes the cycle 0, 1, 2. The cycle-detection lesson needed a DFS over the whole graph. Union-find checks one road at a time, with no adjacency list.
It returns 2 on the city. The cycle check holds for two-way roads only. On the one-way streets 0 → 1, 0 → 2, 1 → 3 and 2 → 3, the last unite returns false, yet no walk leads back to its start.
8 Mistakes, and when to use it
- Joining members, not leaders. After roads 0–1 and 1–2 by rank, everyone points at 1. A road 0–3 written as
parent[0] = 3moves 0 alone. Then find(2) is 1 and find(0) is 3, though roads join 0 and 2. - Comparing parents. In the chain [1, 2, 3, 4, 4, 6, 6],
parent[0]is 1 andparent[2]is 3, yet both lead to 4. Compare find(x) with find(y). - A recursive find on a chain. The short recursive find,
parent[x] = find(parent[x]), makes one call per step. Without union by rank, the first find on a chain of 10⁵ goes 10⁵ calls deep and overflows the stack: Runtime Error. With union by rank it stays under 17 calls. - Numbered from 1. With arrays of size n, the road [6, 7] reads past the end: Runtime Error. Make them n + 1 long.
- Every parent at 0. Then every junction leads to 0, and everything looks connected. Each junction starts as its own parent.
The sign is edges that arrive one at a time, with questions about whether two things are already connected:
- Which edge closes a cycle? The one whose
unitereturns false. - How many groups, or spare edges? Count the true and false results.
- Things that are not numbers. Each email, letter or grid cell gets a number first. A cell at row r and column c can be r × cols + c.
- Group sizes. Keep
sizein place ofrank.
Union-find only joins groups. It cannot remove a road. When the whole graph comes at once with one question, BFS or DFS does the same job. In the next topic, Kruskal's algorithm for minimum spanning trees uses union-find to skip roads that would close a cycle.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.