Number of Connected Components in an Undirected Graph
Medium · Graphs
On LeetCode, Number of Connected Components in an Undirected Graph needs LeetCode Premium (checked October 2026). Here it is free: run and submit in Python, JavaScript, Java or C++ with a free account.
Jump to codeCount connected components among n vertices labeled 0 through n−1, including isolated vertices, given a list of undirected edges.
Examples
Example 1
n = 5 edges = [[0,1],[1,2],[3,4]]
Output: 2
Example 2
n = 5 edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
Constraints
- 1 <= n <= 100
- 0 <= edges.length <= n * (n - 1) / 2
Need a hint?
A traversal from an unseen vertex visits exactly one component.
Asked in real interviews
Candidates reported versions of Number of Connected Components in an Undirected Graph from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Build adjacency lists. Iterate through all n vertices; each unvisited vertex starts a traversal and increases the component count. Mark vertices as they enter the stack or queue. An isolated vertex is a component of size one.
Complexity
O(n + E) time and space.
Python reference solution
def countComponents(n, edges):
neighbors = [[] for _ in range(n)]
for a, b in edges:
neighbors[a].append(b)
neighbors[b].append(a)
seen, count = set(), 0
for start in range(n):
if start in seen:
continue
count += 1
seen.add(start)
stack = [start]
while stack:
for neighbor in neighbors[stack.pop()]:
if neighbor not in seen:
seen.add(neighbor)
stack.append(neighbor)
return count
JavaScript solution
function countComponents(n, edges) {
const neighbors = Array.from({length: n}, () => []);
for (const [a, b] of edges) { neighbors[a].push(b); neighbors[b].push(a); }
const seen = Array(n).fill(false);
let count = 0;
for (let start = 0; start < n; start++) {
if (seen[start]) continue;
count++; seen[start] = true;
const stack = [start];
while (stack.length) {
for (const next of neighbors[stack.pop()]) {
if (!seen[next]) { seen[next] = true; stack.push(next); }
}
}
}
return count;
}
Java solution
import java.util.*;
class Solution {
public int countComponents(int n, int[][] edges) {
List<List<Integer>> neighbors = new ArrayList<>();
for (int i = 0; i < n; i++) neighbors.add(new ArrayList<>());
for (int[] edge : edges) { neighbors.get(edge[0]).add(edge[1]); neighbors.get(edge[1]).add(edge[0]); }
boolean[] seen = new boolean[n];
int count = 0;
for (int start = 0; start < n; start++) {
if (seen[start]) continue;
count++; seen[start] = true;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(start);
while (!stack.isEmpty()) {
for (int next : neighbors.get(stack.pop())) {
if (!seen[next]) { seen[next] = true; stack.push(next); }
}
}
}
return count;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countComponents(int n, vector<vector<int>> &edges) {
vector<vector<int>> neighbors(n);
for (auto& edge : edges) { neighbors[edge[0]].push_back(edge[1]); neighbors[edge[1]].push_back(edge[0]); }
vector<bool> seen(n);
int count = 0;
for (int start = 0; start < n; start++) {
if (seen[start]) continue;
count++; seen[start] = true;
vector<int> pending{start};
while (!pending.empty()) {
int node = pending.back(); pending.pop_back();
for (int next : neighbors[node]) {
if (!seen[next]) { seen[next] = true; pending.push_back(next); }
}
}
}
return count;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
5,
[
[
0,
1
],
[
1,
2
],
[
3,
4
]
]
]2
[
5,
[
[
0,
1
],
[
1,
2
],
[
2,
3
],
[
3,
4
]
]
]1
[ 1, [] ]
1
[
4,
[
[
0,
1
],
[
2,
3
]
]
]2
[
4,
[
[
0,
1
],
[
1,
2
],
[
2,
3
],
[
3,
0
]
]
]1
Drafts are saved per language in this browser when storage is available.