Data Structures & Algorithms / Module 8: Graphs
Topic 8.6
Union-find
Groups that keep merging, and a fast way to ask 'are we in the same group?'.
Watch: everyone points at their boss. Two people are in the same group if their arrows lead to the same leader.
- moving now
- passed / marked
- finished / the result
Group leaders
Picture everyone knowing only who their "boss" is. To find a group's leader, ask your boss, then your boss's boss, until you reach someone who is their own boss. Merging two groups just means telling one leader to report to the other. One pointer changes, however big the groups are.
Two tricks that make it fast
- Union by size: when merging, the smaller group's leader reports to the bigger group's leader, not the other way round. Choose "no rule" in the figure: without this trick the tree can become a chain 5 tall, and find walks it like a linked list.
- Path compression: once find reaches the leader, everyone it passed is pointed straight at that leader. The next question takes one step.
With both, the cost per operation is constant in practice: in theory it grows extremely slowly (the inverse Ackermann function), below 5 for any data size that could exist.
Code, for programmersUnion-find
class UnionFind {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i); // everyone leads themselves
this.size = Array(n).fill(1);
}
find(x) {
if (this.parent[x] !== x) this.parent[x] = this.find(this.parent[x]); // path compression
return this.parent[x];
}
union(a, b) {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already one group
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra];
this.parent[rb] = ra; // small under big
this.size[ra] += this.size[rb];
return true;
}
}Where you meet it
- Merging duplicate accounts: two accounts sharing an email or phone number are treated as one person.
- Kruskal's algorithm: building the cheapest cable network that joins every city, rejecting any cable between two cities already connected.
- Grouping touching pixels in image processing.
- Detecting whether adding an edge would create a cycle in an undirected graph.
Quiz
When are two people in the same group?
What is union by size for?
Which question can union-find not answer?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.