Connected components
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A connected component is a group of items that can all reach one another through links. Counting them with union-find means starting with n groups and subtracting one every time a link joins two different groups.
Practical use cases
- Web app: How many separate friend circles?. A community app wants to show "your platform has 4,200 separate friend circles". Each friendship merges two groups, and every real merge reduces the counter by one. The count is always ready, without searching the graph again. Product managers see the figure change live as friendships form, with no heavy nightly job needed.
- Web app: Outage areas on a status page. A power or internet company shows how many separate pieces its network has split into after faults. Every working cable merges two groups; the number of groups left is the number of isolated areas customers see. The status page therefore updates the number as repairs are logged, rather than recounting the whole network.
- System: Counting islands and image blobs. Counting islands on a map or separate blobs in a photo works the same way, joining neighbouring land or pixels and counting how many different leaders remain. A single pass over the pixels or land cells is enough, and no part of the picture is visited twice.
The story: How Many Friend Circles in Class?
Mrs. Sharma was planning a school trip and needed to seat students on buses. The rule was simple: friends sit together. But who counts as "together"? If Mira is friends with Kabir, and Kabir with Zoya, then Mira and Zoya will end up in the same row too, friends or not.
She had a list of friendships: Mira-Kabir, Kabir-Zoya, Aarav-Raju, and so on. "How many separate friend circles do we have?" she asked. She tried drawing lines on the board, but with forty kids it looked like a plate of noodles.
Mira offered a smarter plan. "Start by saying there are 7 circles, one per kid. Then read each friendship once. If the two kids already share a circle captain, nothing changes. If their captains differ, merge them and subtract one from the count."
After the last friendship, the number left was the number of circles. Those circles have a name in graph language: connected components. Union-Find counts them in a single pass over the list, with no drawing needed.
How to spot this problem, and where you need it
You need to know how many separate clusters exist in a set of items and links, and ideally keep that number up to date as links arrive.
Signs you need it
- The question says "how many groups", "islands", "provinces", "friend circles" or "isolated parts".
- You are running a fresh search of the whole graph each time one link is added.
- Links are given as a list of pairs rather than as a ready graph.
- You only need counts, not the route inside a group.
Where to use it in a project
- Admin dashboards of social, network or logistics features that report cluster counts.
- Map and image tools that label regions or count blobs.
The solution
Make every item its own group and set the counter to n. Go through the links one by one: find the leaders of both ends and, if they differ, union them and reduce the counter by 1. When all links are processed, the counter equals the number of connected components, and each item's leader says which component it is in.
Payoff: Before: re-searching the graph after every new link. After: one tiny update per link and a ready answer at any time.
Explain it like I am 8
Imagine each kid holding a balloon of their own colour. Every time two friends meet, they swap balloons so both have the same colour. At the end, count how many different colours are still in the room.
How it works, step by step
- Make a set for every node and set
count = n. - Read the edges one by one. Each edge is a pair like (Mira, Kabir).
- Try to union the pair. If it returns true, two components really merged, so do
count--. - If it returns false, the pair were already connected (through someone else), so the count stays.
- At the end,
countis the number of components. To list who is in which, group nodes byfind(x).
The code in four languages
PHP
<?php
// Count connected components with union-find (union by size)
function countComponents(int $n, array $edges): array {
$parent = range(0, $n - 1);
$size = array_fill(0, $n, 1);
$find = function (int $x) use (&$parent): int {
while ($parent[$x] !== $x) {
$parent[$x] = $parent[$parent[$x]]; // path halving
$x = $parent[$x];
}
return $x;
};
$count = $n; // start: everyone alone
foreach ($edges as [$a, $b]) {
$ra = $find($a);
$rb = $find($b);
if ($ra === $rb) continue; // already connected
if ($size[$ra] < $size[$rb]) [$ra, $rb] = [$rb, $ra];
$parent[$rb] = $ra;
$size[$ra] += $size[$rb];
$count--; // two circles became one
}
$groups = [];
for ($i = 0; $i < $n; $i++) $groups[$find($i)][] = $i;
return [$count, array_values($groups)];
}
[$count, $groups] = countComponents(7, [[0, 1], [1, 2], [3, 4], [0, 2], [5, 6], [2, 3]]);
echo "circles: " . $count . "\n"; // 2
echo json_encode($groups) . "\n"; // [[0,1,2,3,4],[5,6]]JavaScript
// Count connected components with union-find (union by size)
function countComponents(n, edges) {
const parent = Array.from({ length: n }, (_, i) => i);
const size = Array(n).fill(1);
const find = (x) => {
while (parent[x] !== x) {
parent[x] = parent[parent[x]]; // path halving
x = parent[x];
}
return x;
};
let count = n; // start: everyone alone
for (const [a, b] of edges) {
let ra = find(a);
let rb = find(b);
if (ra === rb) continue; // already connected
if (size[ra] < size[rb]) [ra, rb] = [rb, ra];
parent[rb] = ra;
size[ra] += size[rb];
count--; // two circles became one
}
const groups = {};
for (let i = 0; i < n; i++) (groups[find(i)] = groups[find(i)] || []).push(i);
return [count, Object.values(groups)];
}
const [count, groups] = countComponents(7, [[0, 1], [1, 2], [3, 4], [0, 2], [5, 6], [2, 3]]);
console.log("circles: " + count); // 2
console.log(JSON.stringify(groups)); // [[0,1,2,3,4],[5,6]]Java
import java.util.*;
public class Main {
static int[] parent;
// path halving
static int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
// Count connected components with union-find (union by size)
static int countComponents(int n, int[][] edges, List<List<Integer>> groupsOut) {
parent = new int[n];
int[] size = new int[n];
for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
int count = n; // start: everyone alone
for (int[] e : edges) {
int ra = find(e[0]);
int rb = find(e[1]);
if (ra == rb) continue; // already connected
if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
parent[rb] = ra;
size[ra] += size[rb];
count--; // two circles became one
}
Map<Integer, List<Integer>> groups = new LinkedHashMap<>();
for (int i = 0; i < n; i++) groups.computeIfAbsent(find(i), k -> new ArrayList<>()).add(i);
groupsOut.addAll(groups.values());
return count;
}
public static void main(String[] args) {
int[][] edges = {{0, 1}, {1, 2}, {3, 4}, {0, 2}, {5, 6}, {2, 3}};
List<List<Integer>> groups = new ArrayList<>();
int count = countComponents(7, edges, groups);
System.out.println("circles: " + count); // 2
System.out.println(groups.toString().replace(", ", ",")); // [[0,1,2,3,4],[5,6]]
}
}Go
package main
import "fmt"
// countComponents counts connected components with union-find (union by size).
// It returns the count and the members of each circle.
func countComponents(n int, edges [][2]int) (int, [][]int) {
parent := make([]int, n)
size := make([]int, n)
for i := range parent {
parent[i] = i
size[i] = 1
}
find := func(x int) int {
for parent[x] != x {
parent[x] = parent[parent[x]] // path halving
x = parent[x]
}
return x
}
count := n // start: everyone alone
for _, e := range edges {
ra, rb := find(e[0]), find(e[1])
if ra == rb { // already connected
continue
}
if size[ra] < size[rb] {
ra, rb = rb, ra
}
parent[rb] = ra
size[ra] += size[rb]
count-- // two circles became one
}
var groups [][]int
slot := map[int]int{} // root -> index in groups, in first-seen order
for i := 0; i < n; i++ {
root := find(i)
idx, ok := slot[root]
if !ok {
idx = len(groups)
slot[root] = idx
groups = append(groups, nil)
}
groups[idx] = append(groups[idx], i)
}
return count, groups
}
func main() {
edges := [][2]int{{0, 1}, {1, 2}, {3, 4}, {0, 2}, {5, 6}, {2, 3}}
count, groups := countComponents(7, edges)
fmt.Println("circles:", count) // 2
fmt.Println(groups) // [[0 1 2 3 4] [5 6]]
}Time: O(n + m), almost linear · Extra space: O(n). One quick pass over the m friendships, with each union nearly constant time.
Watch out for
- Decrementing the counter on every edge. Only a union that actually merged two different roots reduces it.
- Counting roots by looking at
parent[i] == ibefore any edges are processed, or counting non-roots by mistake. - Forgetting isolated nodes (kids with no friends). They are components of size one and are already included by starting
count = n.
Quick check
- You start with 7 kids and 3 successful merges. How many circles are left?
- 7
- 4
- 10
- 3
- An edge joins two kids who already share a captain. The count…
- Resets
- Goes down by 1
- Goes up by 1
- Stays the same
- Who is a one-person component?
- A root with many kids
- A kid with two friends
- No one
- A kid with no friendships