Graphs · Pattern 3 of 14
Connected components and union-find
Count or group the separate pieces of a graph. A DFS from every unvisited node works when the graph is fixed; union-find merges groups in almost O(1) when edges arrive one at a time.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- How many groups, provinces or islands are there?
- Edges arrive over time and you ask "are these connected yet?"
- Things that share a key (an email, a row, an index pair) belong together
- Sizes of groups matter: merging, removing or adding one node
The template
static class DSU {
int[] parent, size;
int count; // number of components
DSU(int n) {
parent = new int[n]; size = new int[n]; count = n;
for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
}
int find(int x) {
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } // path halving
return x;
}
boolean unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same component
if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
parent[rb] = ra; // hang the smaller tree under the bigger
size[ra] += size[rb];
count--;
return true;
}
}
int countComponents(int n, int[][] edges) {
DSU d = new DSU(n);
for (int[] e : edges) d.unite(e[0], e[1]);
return d.count;
} class DSU:
def __init__(self, n):
self.parent, self.size, self.count = list(range(n)), [1] * n, n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving
x = self.parent[x]
return x
def unite(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same component
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra # hang the smaller tree under the bigger
self.size[ra] += self.size[rb]
self.count -= 1
return True
def count_components(n, edges):
d = DSU(n)
for a, b in edges:
d.unite(a, b)
return d.count struct DSU {
vector<int> parent, size;
int count; // number of components
DSU(int n) : parent(n), size(n, 1), count(n) { iota(parent.begin(), parent.end(), 0); }
int find(int x) {
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } // path halving
return x;
}
bool unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same component
if (size[ra] < size[rb]) swap(ra, rb);
parent[rb] = ra; // hang the smaller tree under the bigger
size[ra] += size[rb];
count--;
return true;
}
};
int countComponents(int n, vector<vector<int>>& edges) {
DSU d(n);
for (auto& e : edges) d.unite(e[0], e[1]);
return d.count;
} class DSU {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.size = new Array(n).fill(1);
this.count = n; // number of components
}
find(x) {
while (this.parent[x] !== x) {
this.parent[x] = this.parent[this.parent[x]]; // path halving
x = this.parent[x];
}
return x;
}
unite(a, b) {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already in the same component
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra];
this.parent[rb] = ra; // hang the smaller tree under the bigger
this.size[ra] += this.size[rb];
this.count--;
return true;
}
}
function countComponents(n, edges) {
const d = new DSU(n);
for (const [a, b] of edges) d.unite(a, b);
return d.count;
} The variations
-
1Count the components
Run a DFS (or union-find) from every node that has not been seen yet; each new start is a new component. Spare edges (unions that return false) can rewire the graph: you need
components − 1of them.Now you solve -
2Edges that arrive over time
Union-find answers "how many groups now?" after every new edge or new land cell, without searching again. Sort friendships by time and stop at the first moment the count reaches 1.
Now you solve -
3Union by a shared key
Join items that share something: the same email, the same row or column, two swappable indexes, or
a == b. Then each group can be treated as one: sort its letters, merge its accounts, or check every!=against it.Now you solve -
4Weighted edges: ratios along a path
For
a / b = 2, add the edge a → b with weight 2 and b → a with 1/2. A queryx / yis the product of the weights along any path from x to y (a DFS), or −1 when they are in different components. -
5Use the component sizes
Label each component and store its size. Then ask what one change does: flipping a 0 joins the distinct neighbouring islands (add their sizes + 1), and removing an infected node saves its component only if it is the only infected node there.
Now you solve
Mistakes to avoid
- Comparing
parent[a] == parent[b]instead offind(a) == find(b): parents are not roots until you follow them all the way up. - Counting components with a DFS from node 0 only. Loop over every node and start a new search from each one not yet visited.
- Forgetting that
unitereturning false means the edge closed a loop: that is exactly the spare cable in "make the network connected".
Lesson done
Next: BFS for the shortest path →Mark it done once you can write the template from memory and you have solved the worked examples yourself.