Union-Find
Advanced · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Union-Find keeps track of which items belong to the same group, with two fast operations: merge two groups, and ask "are these two in the same group?". It never needs to list the members.
Practical use cases
- Web app: Merging duplicate customer accounts. A CRM finds pairs of records that look like the same person (same phone, same email). Each match merges two groups, and afterwards any two records can be asked whether they belong to the same person, so a million messy rows become clean customer profiles.
- Web app: Friend circles and community detection. A social app wants to know whether two users are in the same connected circle. Each new friendship merges two circles, and asking "same circle?" stays instant, even for millions of users.
- Web app: Network connectivity monitor. An admin page shows whether any two offices can still reach each other as new links go up. Every new link merges two groups, so the map of connected offices updates the instant a link is added.
- System: Kruskal's cheapest network and image segmentation. Building the cheapest cable network means adding the cheapest link that does not create a loop, which Union-Find checks. Image tools use it to join touching pixels into regions in one quick pass.
The story: The Friend Circles of Mohalla
In Zoya’s mohalla, friendships kept forming. "Aarav and Kabir became friends!" "Mira and Zoya too!" Then Aarav and Mira became friends, which suddenly joined two whole gangs into one. The cricket captain kept asking: "Are Kabir and Zoya in the same gang? How many gangs are there?"
Zoya tried keeping a list of every gang’s members. Each time two gangs joined she copied and merged lists, and every question meant scanning lists. Too slow when hundreds of kids joined.
Grandpa Bhaskar suggested a trick: "Give every gang a leader. Each child just remembers one name: who they follow. To check whether two kids are in the same gang, follow the leader chain until the top and compare the tops. To join two gangs, make one leader follow the other." Two tiny operations: find (who leads you) and union (join gangs).
That is Union-Find, also called the disjoint-set union. The smell: "are these two connected?", "number of groups / provinces / components", "merge groups over time", "redundant connection", "accounts that belong to the same person". Friendships keep arriving, and you only need to know who is in the same group.
How to spot this problem, and where you need it
Items keep getting joined into groups, and you must quickly tell whether two items are already in the same group, without re-searching the whole network every time.
Signs you need it
- The wording is "connected", "same group", "merge groups", "number of components" or "would this link create a loop".
- You are running a full graph search for each yes/no question about connection.
- Connections only get added over time, never removed.
Where to use it in a project
- Duplicate detection and record merging in customer or contact databases.
- Network, friend or cluster connectivity checks that update as new links appear.
- Cheapest-network building and loop prevention in planning tools.
The solution
Give each item a "parent" pointer, starting at itself. To find an item's group leader, follow parents to the top, and flatten the path as you go so next time it is shorter. To merge two groups, find both leaders and make one point to the other, attaching the smaller to the larger. Two items are in the same group exactly when their leaders match.
Payoff: Before: a full search of the network for each question. After: a handful of pointer hops, nearly instant even for millions of items.
Explain it like I am 8
Every group of friends picks one captain. Each kid only remembers who they follow. To see whether two kids are friends of friends, ask each "who is your captain at the very top?" If it is the same captain, they are in one team. To merge teams, one captain simply starts following the other.
How it works, step by step
- Spot the clue: items get merged into groups over time, and you ask "same group?" or "how many groups?".
- Start: every item is its own leader (
parent[i] = i) and the group count equals n. - find(x): follow
parentuntil an item is its own parent. Speed-up: path compression, point the items you pass straight at the leader. - union(a, b): find both leaders. If they differ, hang one under the other and reduce the group count. If equal, they were already connected.
- Answer: "same group?" is
find(a) === find(b); "how many groups?" is the counter.
The code in four languages
PHP
<?php
// Classic: "Number of Provinces": groups of connected friends.
class UnionFind {
private array $parent;
public int $groups;
public function __construct(int $n) {
$this->parent = range(0, $n - 1); // everyone leads themselves
$this->groups = $n;
}
public function find(int $x): int {
while ($this->parent[$x] !== $x) {
$this->parent[$x] = $this->parent[$this->parent[$x]]; // path compression (shortcut)
$x = $this->parent[$x];
}
return $x;
}
public function union(int $a, int $b): bool {
$ra = $this->find($a);
$rb = $this->find($b);
if ($ra === $rb) return false; // already in the same group
$this->parent[$rb] = $ra; // one leader follows the other
$this->groups--;
return true;
}
}
$uf = new UnionFind(6);
foreach ([[0, 1], [2, 3], [1, 3], [4, 5], [0, 3]] as [$a, $b]) {
$uf->union($a, $b);
}
echo "groups: ", $uf->groups, "
"; // 2
echo "1 and 3 friends? ", var_export($uf->find(1) === $uf->find(3), true), "
"; // true
echo "1 and 5 friends? ", var_export($uf->find(1) === $uf->find(5), true), "
"; // falseJavaScript
// Classic: "Number of Provinces": groups of connected friends.
class UnionFind {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i); // everyone leads themselves
this.groups = n;
}
find(x) {
while (this.parent[x] !== x) {
this.parent[x] = this.parent[this.parent[x]]; // path compression (shortcut)
x = this.parent[x];
}
return x;
}
union(a, b) {
const ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already in the same group
this.parent[rb] = ra; // one leader follows the other
this.groups--;
return true;
}
}
const uf = new UnionFind(6);
for (const [a, b] of [[0, 1], [2, 3], [1, 3], [4, 5], [0, 3]]) {
uf.union(a, b);
}
console.log('groups: ' + uf.groups); // 2
console.log('1 and 3 friends? ' + (uf.find(1) === uf.find(3))); // true
console.log('1 and 5 friends? ' + (uf.find(1) === uf.find(5))); // falseJava
public class Main {
// Classic: "Number of Provinces": groups of connected friends.
static class UnionFind {
private final int[] parent;
int groups;
UnionFind(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i; // everyone leads themselves
groups = n;
}
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // path compression (shortcut)
x = parent[x];
}
return x;
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
parent[rb] = ra; // one leader follows the other
groups--;
return true;
}
}
public static void main(String[] args) {
UnionFind uf = new UnionFind(6);
int[][] pairs = {{0, 1}, {2, 3}, {1, 3}, {4, 5}, {0, 3}};
for (int[] p : pairs) {
uf.union(p[0], p[1]);
}
System.out.println("groups: " + uf.groups); // 2
System.out.println("1 and 3 friends? " + (uf.find(1) == uf.find(3))); // true
System.out.println("1 and 5 friends? " + (uf.find(1) == uf.find(5))); // false
}
}Go
package main
import "fmt"
// UnionFind is the classic "Number of Provinces": groups of connected friends.
type UnionFind struct {
parent []int
groups int
}
func NewUnionFind(n int) *UnionFind {
parent := make([]int, n)
for i := range parent {
parent[i] = i // everyone leads themselves
}
return &UnionFind{parent, n}
}
func (u *UnionFind) Find(x int) int {
for u.parent[x] != x {
u.parent[x] = u.parent[u.parent[x]] // path compression (shortcut)
x = u.parent[x]
}
return x
}
func (u *UnionFind) Union(a, b int) bool {
ra, rb := u.Find(a), u.Find(b)
if ra == rb {
return false // already in the same group
}
u.parent[rb] = ra // one leader follows the other
u.groups--
return true
}
func main() {
uf := NewUnionFind(6)
for _, p := range [][2]int{{0, 1}, {2, 3}, {1, 3}, {4, 5}, {0, 3}} {
uf.Union(p[0], p[1])
}
fmt.Println("groups:", uf.groups) // 2
fmt.Println("1 and 3 friends?", uf.Find(1) == uf.Find(3)) // true
fmt.Println("1 and 5 friends?", uf.Find(1) == uf.Find(5)) // false
}Time: Almost O(1) per operation · Extra space: O(n). With path compression each find or union is nearly constant time, so m operations cost about O(m).
Watch out for
- Comparing
parent[a] === parent[b]instead of the true leaders fromfind. Parents are not always leaders. - Forgetting to decrement the group counter only when a real merge happens.
- Merging the items themselves instead of their leaders, which breaks the groups.
Quick check
- Which phrase smells like Union-Find?
- "merge overlapping meetings"
- "keep merging groups and ask if two are connected"
- "find the maximum subarray"
- "reverse a list"
- How do you check if A and B are in the same group?
- Compare their indexes
- Compare parent[A] and parent[B] only
- Compare find(A) and find(B)
- Sort the groups
- union(a, b) where both share a leader should...
- Merge them again
- Increase the group count
- Delete the leader
- Do nothing, and the group count stays