Merge groups and ask whether two items are connected, almost in constant time.
You work on a payments app. Some customers open a second account by mistake. A matching job finds pairs of accounts that belong to the same person. It sends you one link at a time: the link a b means that accounts a and b are the same customer.
Here are eight accounts, numbered 0 to 7, and the links in the order they arrive.
0 1
2 3
4 5
1 3
5 6
3 5
6 2
7 1After the link 1 3, accounts 0, 1, 2 and 3 are all one customer. No link joins 0 and 2 directly, but the chain 0 to 1, 1 to 3 and 3 to 2 does.
A group is a set of accounts joined by a chain of links, long or short. Two accounts are connected when they are in the same group. In graph words, the accounts are vertices, the links are edges, and the groups are the connected components. You met graphs in Graphs (S6).
Your team lead says: "After every link, I want to ask whether two accounts are the same customer, and how many customers we have." The links never stop, and the questions come in between them.
The first attempt is correct. Keep the links as a graph. To answer "are x and y connected", search from x with the BFS or DFS of BFS and DFS on a grid (A1). See whether y turns up.
One search can visit every account and every link, so it costs O(n + m). With 100,000 accounts, 200,000 links and 100,000 questions, that is about 30 billion steps.
A second attempt writes a group number next to each account, so a question is one comparison. But a link must then rename a whole group, which can touch nearly every account. Over 100,000 links, the worst case is billions of steps.
Both attempts do their work at the wrong moment. We want a link to be cheap, a question to be cheap, and nobody to be renamed.
Think of companies that merge. Every person knows only their own manager. To learn which company someone works for, you follow the managers upward until you reach a person with no manager: the head. Two people work for the same company when they reach the same head.
When two companies merge, nobody changes their own manager. One head starts to report to the other head. The head of the smaller company goes under the head of the larger one, so chains of command stay short.
Each time you walk up a chain, you tell everyone you passed who the head is. From then on they report straight to the head.
In the code, a person is an account, a manager is a parent pointer, the head is the root, and a company is a group. The picture is wrong in one way: real people change jobs, but a group never splits.
Union-find works like companies that merge: follow the managers to the head, and the smaller company's head goes under the larger one's.
Union-find, also called a disjoint set union (DSU), keeps items in groups that never overlap. It has two operations.
find(x) returns the root of x's group.union(a, b) merges the group of a with the group of b.Two items are connected exactly when find gives the same root for both.
Predict what happens
Q The links 0 1, then 2 3, then 1 3 have arrived. Are accounts 0 and 2 the same customer?
Answer: B
A group is every account joined by a chain of links, so a link between 1 and 3 joins their whole groups. Accounts 0 and 2 are connected through 1 and 3.
Union-find keeps two arrays.
parent[i] is the parent of account i. At the start every account is its own parent, so every account is a root in a group of one.size[r] is the number of accounts in the tree whose root is r. Only a root's size is up to date.The picture draws each account as a circle with an arrow to its parent. A root has no arrow out. Each tree is one group, and all the trees together are a forest.
find(x) walks up from x: x, then parent[x], then its parent, and so on, until it reaches an account that is its own parent. That is the root. Then it does path compression: every account on the walk is pointed straight at the root.
union(a, b) finds both roots, ra and rb. If they are the same, the two accounts are already one group, so nothing changes. If they differ, the root of the smaller tree goes under the root of the larger one, and the larger root's size grows by the smaller size.
This is union by size. When the sizes are equal, rb goes under ra.
To count groups, start at n. Each union that links two different roots lowers the count by 1.
Here is each link, with the roots found and the parent array afterwards. The groups column is the count of groups after the link.
| Link | Roots found | What happens | parent after |
Groups |
|---|---|---|---|---|
| start | every account is its own root | [0,1,2,3,4,5,6,7] |
8 | |
0 1 |
0 and 1 | equal sizes, so 1 goes under 0 | [0,0,2,3,4,5,6,7] |
7 |
2 3 |
2 and 3 | equal sizes, so 3 goes under 2 | [0,0,2,2,4,5,6,7] |
6 |
4 5 |
4 and 5 | equal sizes, so 5 goes under 4 | [0,0,2,2,4,4,6,7] |
5 |
1 3 |
0 and 2 | sizes 2 and 2, so 2 goes under 0 | [0,0,0,2,4,4,6,7] |
4 |
5 6 |
4 and 6 | sizes 2 and 1, so 6 goes under 4 | [0,0,0,2,4,4,4,7] |
3 |
3 5 |
0 and 4 | find(3) walks 3, 2, 0 and points 3 at 0. Sizes 4 and 3, so 4 goes under 0 | [0,0,0,0,0,4,4,7] |
2 |
6 2 |
0 and 0 | find(6) walks 6, 4, 0 and points 6 at 0. Same root: nothing to link | [0,0,0,0,0,4,0,7] |
2 |
7 1 |
7 and 0 | sizes 1 and 7, so 7 goes under 0 | [0,0,0,0,0,4,0,0] |
1 |
Look at the link 3 5. Before it, account 3 was two steps below its root. After the find, parent[3] is 0, so the next find from 3 takes one step. That is path compression.
Find walks up to the root, then path compression points every account on the walk straight at it, so the next find is short.
Exercise · Predict the output: What does one find change?. Six accounts, where `parent` is [0, 0, 1, 2, 3, 3]: account 4 hangs below 3, 2 and 1, and account 5 hangs below 3. One find from account 4 runs with path compression. What does `parent` look like afterwards?
parent = [0, 0, 1, 2, 3, 3]
x = 4
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
up = parent[x]
parent[x] = root
x = up
print(*parent)Step by step: Union-find on the eight accounts. The animated player loads in your browser.
Now look at how the size decides the direction. In the link 5 6, the tree of 4 had two accounts and the tree of 6 had one, so 6 went under 4. The bigger tree's root stays on top, so the accounts of the bigger tree do not get any deeper.
Union by size puts the smaller tree's root under the larger one, so the same links make a short star instead of a long chain.
Predict what happens
Q The array is [0,0,0,0,0,4,4,7], and group 0 has 7 accounts. The link 6 2 arrives. What does union do?
Answer: C
The roots are equal, so the accounts are already connected. A union that finds equal roots changes no link and no count. The find from 6 does point 6 straight at 0.
The link 6 2 was a surprise. Accounts 6 and 2 were already connected through the chain 6, 5, 3, 2, which came from the links 5 6, 3 5 and 2 3. The new link tells us nothing new, and in the graph it closes a cycle: a path of links that leads back to where it started.
Union-find sees this at once, because both roots are equal. Any link that joins two accounts with the same root closes a cycle.
A link between two accounts that already have the same root adds nothing: in a graph it closes a loop.
Pick a map and run union-find step by step. Go forwards and back.
Try these four, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
find ends at the root, so two accounts have the same root exactly when they are in the same tree. A union that links one root under the other joins the two trees into one tree, and so joins the two groups. No other tree changes.
Every item sits in one tree, and two items are in the same group exactly when their trees have the same root. Linking one root under another merges two groups and leaves every other group alone.
Follow one account, say account 6. Its depth grows by 1 only when its root goes under another root. That happens only when its tree is the smaller one, or equal in size. So the merged tree has at least twice as many accounts as the tree that 6 was in.
A tree never has more than n accounts, so the size of 6's tree can double at most log2 n times. No account is deeper than log2 n. For 100,000 accounts that is at most 16 steps. Path compression only moves accounts up, so this limit still holds.
Many textbooks use union by rank instead. Each root keeps a rank, an upper bound on the height of its tree, and the root with the lower rank goes under. It gives the same log2 n limit, and with path compression the same nearly constant cost.
A find that walks k steps costs k. After it, those k accounts all point straight at the root, so a find from any of them takes 1 step. The long walk makes the next walks short.
Spread over many calls, the cost per call is small. That is amortised cost: the total cost of a run of operations, divided by the number of operations. One find can still be slow, at most log2 n steps, but a long run of finds cannot all be slow.
Exercise · Put it in order: find with path compression. Arrange the lines into find. It walks up to the root, then points every account on the walk straight at the root, and returns the root.
def find(parent, x):
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
up = parent[x]
parent[x] = root
x = up
return root
x = parent[x]Predict what happens
Q A bug links the bigger tree's root under the smaller tree's root every time. What can go wrong?
Answer: B
Linking one root under another always merges the two groups, so the answers stay correct. Only the shape changes. Always putting the bigger tree underneath can build a tall chain, and a find then walks it step by step.
Union by size alone makes every find take at most log2 n steps. Path compression alone brings the average cost down to about log n per operation. With both, the cost drops further. Building n accounts and then doing m finds and unions costs O((n + m) α(n)) in total.
Here α is the inverse Ackermann function. It grows more slowly than any function you will meet in practice. It is at most 4 for every n below 10^80, which is far more than any computer can hold.
We name it and do not derive it, because the proof is long. In practice you treat each find and union as nearly constant time, or "nearly O(1)".
Start with n groups. Each union that links two different roots joins two groups into one, so the count drops by exactly 1. A union that finds equal roots changes nothing. So the count of groups is n minus the number of successful unions.
The same rule finds a cycle in an undirected graph. Take the edges one at a time. An edge whose two ends already have the same root closes a loop.
If m edges join n vertices into c groups, exactly n minus c edges were successful unions, so exactly m − n + c edges closed a loop. In the eight-account example, m = 8, n = 8 and c = 1, so one link closed a loop. That was 6 2.
Exercise · Break it: Union-find on one-way dependencies. This check reports a cycle when a rule joins two items that already share a root. The rules are one-way: a b means a comes before b. Find a set of rules where it reports a cycle that does not exist.
def has_cycle(n, edges):
parent = list(range(n))
def find(x):
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
up = parent[x]
parent[x] = root
x = up
return root
for a, b in edges:
ra, rb = find(a), find(b)
if ra == rb:
return True
parent[rb] = ra
return FalseHere is union-find as code. dsu_scan applies a list of links and returns two numbers: how many groups are left, and how many links closed a loop. The step markers [1] to [7] match the steps above. Both walks in find use loops, so a long chain cannot overflow the call stack.
class DSU:
def __init__(self, n):
# [1] Every item starts as its own group: its own parent, size 1.
self.parent = list(range(n))
self.size = [1] * n
self.groups = n
def find(self, x):
# [2] Walk up to the root.
root = x
while self.parent[root] != root:
root = self.parent[root]
# [3] Path compression: point every item on the walk straight at the root.
while self.parent[x] != root:
up = self.parent[x]
self.parent[x] = root
x = up
return root
def union(self, a, b):
# [4] Find both roots. The same root means they are already one group.
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
# [5] Link the smaller tree's root under the larger tree's root.
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
# [6] Two groups became one.
self.groups -= 1
return True
def dsu_scan(n, links):
dsu = DSU(n)
redundant = 0
for a, b in links:
# [7] A link between items already in one group closes a loop: count it.
if not dsu.union(a, b):
redundant += 1
return [dsu.groups, redundant]static class DSU {
int[] parent;
int[] size;
int groups;
DSU(int n) {
// [1] Every item starts as its own group: its own parent, size 1.
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
groups = n;
}
int find(int x) {
// [2] Walk up to the root.
int root = x;
while (parent[root] != root) root = parent[root];
// [3] Path compression: point every item on the walk straight at the root.
while (parent[x] != root) {
int up = parent[x];
parent[x] = root;
x = up;
}
return root;
}
boolean union(int a, int b) {
// [4] Find both roots. The same root means they are already one group.
int ra = find(a), rb = find(b);
if (ra == rb) return false;
// [5] Link the smaller tree's root under the larger tree's root.
if (size[ra] < size[rb]) {
int t = ra;
ra = rb;
rb = t;
}
parent[rb] = ra;
size[ra] += size[rb];
// [6] Two groups became one.
groups--;
return true;
}
}
public int[] dsuScan(int n, int[][] links) {
DSU dsu = new DSU(n);
int redundant = 0;
for (int[] link : links) {
// [7] A link between items already in one group closes a loop: count it.
if (!dsu.union(link[0], link[1])) redundant++;
}
return new int[] { dsu.groups, redundant };
}struct DSU {
vector<int> parent;
vector<int> size;
int groups;
DSU(int n) {
// [1] Every item starts as its own group: its own parent, size 1.
parent.resize(n);
size.assign(n, 1);
for (int i = 0; i < n; i++) parent[i] = i;
groups = n;
}
int find(int x) {
// [2] Walk up to the root.
int root = x;
while (parent[root] != root) root = parent[root];
// [3] Path compression: point every item on the walk straight at the root.
while (parent[x] != root) {
int up = parent[x];
parent[x] = root;
x = up;
}
return root;
}
bool unite(int a, int b) {
// [4] Find both roots. The same root means they are already one group.
int ra = find(a), rb = find(b);
if (ra == rb) return false;
// [5] Link the smaller tree's root under the larger tree's root.
if (size[ra] < size[rb]) swap(ra, rb);
parent[rb] = ra;
size[ra] += size[rb];
// [6] Two groups became one.
groups--;
return true;
}
};
vector<int> dsuScan(int n, vector<vector<int>> links) {
DSU dsu(n);
int redundant = 0;
for (auto& link : links) {
// [7] A link between items already in one group closes a loop: count it.
if (!dsu.unite(link[0], link[1])) redundant++;
}
return {dsu.groups, redundant};
}class DSU {
constructor(n) {
// [1] Every item starts as its own group: its own parent, size 1.
this.parent = Array.from({ length: n }, (_, i) => i);
this.size = new Array(n).fill(1);
this.groups = n;
}
find(x) {
// [2] Walk up to the root.
let root = x;
while (this.parent[root] !== root) root = this.parent[root];
// [3] Path compression: point every item on the walk straight at the root.
while (this.parent[x] !== root) {
const up = this.parent[x];
this.parent[x] = root;
x = up;
}
return root;
}
union(a, b) {
// [4] Find both roots. The same root means they are already one group.
let ra = this.find(a);
let rb = this.find(b);
if (ra === rb) return false;
// [5] Link the smaller tree's root under the larger tree's root.
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra];
this.parent[rb] = ra;
this.size[ra] += this.size[rb];
// [6] Two groups became one.
this.groups--;
return true;
}
}
function dsuScan(n, links) {
const dsu = new DSU(n);
let redundant = 0;
for (const [a, b] of links) {
// [7] A link between items already in one group closes a loop: count it.
if (!dsu.union(a, b)) redundant++;
}
return [dsu.groups, redundant];
}On the eight-account example this returns [1, 1]: one group, and one link that closed a loop. When the items are names or email addresses instead of numbers, first give each distinct one a number with a hash map, then use the numbers.
Exercise · Find the bug: Every link looks like a loop. This scan should count the links that joined two accounts already in one group. It counts every link, including the first one. Which line is wrong?
def dsu_scan(n, links):
parent = list(range(n))
def find(x):
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
up = parent[x]
parent[x] = root
x = up
return root
groups, loops = n, 0
for a, b in links:
ra, rb = find(a), find(b)
if ra != rb:
parent[rb] = ra
groups -= 1
if find(a) == find(b):
loops += 1
return [groups, loops]Predict what happens
Q A call to dsu_scan on 5 items gets the links 0 1, 0 1 and 1 0. What does it return?
Answer: B
The first link joins 0 and 1, leaving 4 groups. The links 0 1 and 1 0 then find equal roots, so each counts as a link that closed a loop. A repeated link is a loop of two.
Now write the class yourself. The lab has one function, dsu_run(n, ops). It creates a union-find over n accounts and applies a list of operations in order.
Each operation is a row [kind, a, b]. The function returns one answer for each row.
| kind | operation | what to return |
|---|---|---|
| 0 | union(a, b) |
1 if two groups were merged, 0 if a and b were already connected |
| 1 | connected(a, b) |
1 if a and b are in the same group, 0 if not |
| 2 | count() |
the number of groups now (a and b are 0 and are ignored) |
| 3 | size_of(a) |
the number of accounts in a's group (b is 0 and is ignored) |
Put the work in a small class with find, union, connected and count, as in the code above. Three rules keep it correct:
find(a) == find(b).Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Group numbers (rename a group) | Parent pointers, no tricks | Union-find (size and compression) |
|---|---|---|---|
| Time of one find | O(1) | O(n) worst case: a chain | Amortised O(α(n)); one find at most log2 n steps |
| Time of one union | O(n) worst case: rename a group | O(n) worst case: two finds | Amortised O(α(n)); at most log2 n steps for its two finds |
| Memory | O(n) | O(n) | O(n): a parent and a size for each item |
| Counting groups | O(1) with a counter | O(1) with a counter | O(1) with a counter |
For 100,000 accounts and 300,000 operations, even if every find took the full 16 steps, the total would be about 10 million steps. In practice it is far fewer. Setting up the arrays costs O(n). The cost of one find is "nearly constant" in the amortised sense: the total over a run is small, even when one find is longer than the rest.
Use union-find when items join groups and never leave, and you keep asking whether two items are in the same group. Duplicate accounts, friend circles, machines on a network and "these two are the same" rules all fit.
It is the right tool when links arrive one at a time and you need an answer between them. It also counts groups as links arrive, and finds the first link that closes a loop in an undirected graph.
Do not use it when a group must split. There is no "undo a link": if links can be removed, you need a different method, or you process the links in reverse.
Do not use it when you need the route between two items or its length. Union-find says that two items are connected, not how. For paths use the search of A1, or Dijkstra's algorithm.
Do not use it for directed edges, where a to b does not mean b to a. For a directed graph use the topological sort of A3.
If the graph never changes and you ask once, one BFS or DFS is as good.
Writing parent[a] = b for a link looks right, but a may not be a root. After the link 0 1, account 1 points at 0. The link 1 3 with parent[1] = 3 moves 1 away from 0, so 0 and 1 stop being in the same group. Always find both roots first and link parent[rb] = ra.
Always link the roots: writing parent of one equals three when one is not a root pulls account one away from its own group.
parent[a] == parent[b] is true only for items that point at the same parent. After the first four links parent is [0,0,0,2,4,4,6,7]. Accounts 1 and 3 are the same customer, but parent[1] is 0 and parent[3] is 2. Compare find(a) == find(b).
groups -= 1 on every link counts a loop as a merge. On the eight links it would end at 0 groups, and the real answer is 1. Lower the count only when the two roots differ.
size[x] is up to date only when x is a root. After the link 0 1, size[1] is still 1, while the group of 1 has 2 accounts. Read size[find(x)].
For if find(a) == find(b): cycle, take three one-way dependencies: 0 to 1, 1 to 2 and 0 to 2. The third arrow joins two items that are already connected, so union-find reports a cycle. But 0, 1, 2 is a valid order, and there is no cycle. Union-find ignores direction, so use it only for undirected graphs.
find returns a group's root, and union merges two groups. Two items are connected when their roots are equal.Explain the two tricks in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Groups and roots
Q1/2 Links 0 1, 1 2 and 3 4 have arrived. Which pair of accounts is connected?
Answer: B
A chain of links joins 0, 1 and 2, so 0 and 2 are connected even though no link joins them directly. Accounts 3 and 4 form a separate group.
Q2/2 What does find(x) return?
Answer: C
find follows parent pointers up until it reaches an item that is its own parent. That root stands for the whole group.
Checkpoint · Union and size
Q1/2 union(a, b) finds that the roots are 5 with a group of 4 items, and 9 with a group of 2 items. What does union by size do?
Answer: B
Union by size puts the root of the smaller tree under the root of the larger one. Here 9 goes under 5, and the size of 5 becomes 6.
Q2/2 Why does union by size keep every tree no taller than log2 n?
Answer: C
An item's depth grows by 1 only when its tree goes under a tree at least as large. The merged tree has at least twice as many items, and the size cannot double more than log2 n times.
Checkpoint · Path compression and cost
Q1/2 The parent array is [0,0,2,2,3] and find(4) is called. What does the array hold after it?
Answer: B
The walk goes 4, 3, 2 and stops at the root 2. Path compression points every item on the walk straight at 2, so parent[4] becomes 2. Item 3 already points at 2.
Q2/2 Which statement about the cost of union-find with both tricks is right?
Answer: C
The bound is amortised: the total of a run divided by its length. α is the inverse Ackermann function, at most 4 for any n below 10^80. One find can still be longer than the average.
Checkpoint · Counting and cycles
Q1/2 There are 10 accounts. Seven links arrive, and union finds equal roots for two of them. How many groups are left?
Answer: C
Only the 5 links that joined two different roots lowered the count: 10 minus 5 is 5. The 2 links with equal roots changed nothing.
Q2/2 You take the edges of an undirected graph one at a time. When does an edge close a cycle?
Answer: C
Equal roots mean the ends were already joined by a chain of earlier edges. The new edge adds a second route between them: a loop.
Checkpoint · Limits
Q1/2 Which job is union-find not suited to?
Answer: C
Union-find only merges groups. It has no way to undo a link. It handles the other three jobs well.
Q2/2 A graph has one-way edges 0 to 1, 1 to 2 and 0 to 2. Union-find says the third edge closes a cycle. Is there a directed cycle?
Answer: C
A directed cycle needs the arrows to lead back to the start, and here they do not. Union-find treats each edge as two-way, so it only suits undirected graphs.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.