Number of Connected Components in an Undirected Graph
Medium
Topics
Given n nodes labeled 0..n-1 and a list of undirected edges, return the number of connected components.
Example 1
Each shade is one connected component: a group of nodes reachable from one another. Isolated nodes count too, which is the usual off-by-one. There are 2.
Nodes are drawn on a circle; an edge list says nothing about layout, only about connections.
Input: n = 5, edges = [[0,1],[1,2],[3,4]] Output: 2
Example 2
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]] Output: 1
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
Editorial — intuition, approach, complexity and pitfalls
Intuition
Start with n isolated components. Each edge that joins two different components reduces the count by one — that is exactly what union-find tracks.
Approach
- Initialize a DSU with each node its own parent and a component count of n.
- For each edge, union the endpoints; if they were in different sets, decrement the count.
- Return the final count.
Dry Run
n = 5, edges 0-1 1-2 3-4
Start by assuming the worst: every node is its own component.
comp = 5 par [0, 1, 2, 3, 4]
edge 0-1 roots 0 and 1 differ -> merge, comp = 4 par [1, 1, 2, 3, 4]
edge 1-2 roots 1 and 2 differ -> merge, comp = 3 par [1, 2, 2, 3, 4]
edge 3-4 roots 3 and 4 differ -> merge, comp = 2 par [1, 2, 2, 4, 4]
answer 2 -- {0, 1, 2} and {3, 4}
Counting down from n rather than up from 0 is what avoids a second pass. Every
successful union reduces the count by exactly one, because it replaces two
components with one; no traversal is needed at the end to find out how many
survived.
The `ra != rb` guard is the part that has to be right. An edge whose endpoints are
already in the same component merges nothing, so decrementing for it counts a
merge that never happened. Drop the guard and two isolated nodes with the
self-loops 0-0 and 1-1 report 0 components instead of 2.
Path compression inside find -- `par[x] = par[par[x]]` -- is what keeps this near
linear. Without it a chain of unions degrades into a linked list and every find
walks its whole length.Complexity
- Time — O((V+E) alpha): near-constant union-find operations.
- Space — O(V): the parent array.
Common Pitfalls
- Only decrement when the roots actually differ. A self-loop or a repeated edge otherwise counts as a merge that never happened: two isolated nodes with edges
0-0and1-1report 0 components instead of 2. - Path compression in
findis what keeps this near-linear. Without it a chain of unions degrades to a linked list and each find walks it.
Full Solution — all languages
class Solution:
def countComponents(self, n, edges):
par=list(range(n))
def find(x):
while par[x]!=x:
par[x]=par[par[x]]; x=par[x]
return x
comp=n
for a,b in edges:
ra,rb=find(a),find(b)
if ra!=rb: par[ra]=rb; comp-=1
return compimport java.util.*;
class Solution {
public int countComponents(int n, int[][] edges) {
int[] par=new int[n];
for(int i=0;i<n;i++)par[i]=i;
int comp=n;
for(int[] e:edges) {
int ra=find(par,e[0]),rb=find(par,e[1]);
if(ra!=rb) {
par[ra]=rb;
comp--;
}
}
return comp;
}
int find(int[] par,int x) {
while(par[x]!=x) {
par[x]=par[par[x]];
x=par[x];
}
return x;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int countComponents(int n, vector<vector<int>>& edges) {
vector<int> par(n);
for(int i=0;i<n;i++)par[i]=i;
function<int(int)> find=[&](int x) {
while(par[x]!=x) {
par[x]=par[par[x]];
x=par[x];
}
return x;
};
int comp=n;
for(auto& e:edges) {
int ra=find(e[0]),rb=find(e[1]);
if(ra!=rb) {
par[ra]=rb;
comp--;
}
}
return comp;
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/ var countComponents = function(n, edges) {
const par=[];
for(let i=0;i<n;i++)par[i]=i;
function find(x) {
while(par[x]!==x) {
par[x]=par[par[x]];
x=par[x];
}
return x;
}
let comp=n;
for(const e of edges) {
const ra=find(e[0]),rb=find(e[1]);
if(ra!==rb) {
par[ra]=rb;
comp--;
}
}
return comp;
};