Count Connected Components
Published at25 Jul 2026
Created by M Ichsanul Fadhil
Given n nodes labeled from 0 to n-1 and an undirected edge list, count the number of connected components in the graph using DFS.
Build an adjacency list from the edges. Use a visited array. For each unvisited node, run DFS to visit all reachable nodes and increment the component count.
Time is O(n + e) where e is the number of edges. Space is O(n + e) for the adjacency list.
Example Input & Output
Example 1
Input
5,[[0,1],[1,2],[3,4]]
Output
2
Explanation
Two components: {0,1,2} and {3,4}
Example 2
Input
3,[]
Output
3
Explanation
No edges: each node is its own component
Example 3
Input
1,[]
Output
1
Explanation
Single node
Example 4
Input
3,[[0,1],[1,2]]
Output
1
Explanation
3 nodes, 2 edges: one component
Example 5
Input
4,[[0,1],[1,2],[2,3]]
Output
1
Explanation
Chain: one component
Algorithm Flow

Recommendation Algorithm Flow for Count Connected Components
Solution Approach
Best Answers
java
import java.util.*;
class Solution {
public int solution(int n, int[][] e) {
List<Integer>[] adj=new ArrayList[n];for(int i=0;i<n;i++)adj[i]=new ArrayList<>();
for(int[] p:e){adj[p[0]].add(p[1]);adj[p[1]].add(p[0]);}
boolean[] v=new boolean[n];int c=0;
for(int i=0;i<n;i++){if(!v[i]){c++;dfs(i,adj,v);}}
return c;
}
void dfs(int u,List<Integer>[] adj,boolean[] v){
v[u]=true;for(int w:adj[u]){if(!v[w])dfs(w,adj,v);}
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
