Count Connected Components
Given an adjacency list representing an undirected graph with n nodes (0 to n-1), count the number of connected components. A connected component is a group of nodes that are reachable from each other through edges.
For example, with n=5 and edges [[0,1],[1,2],[3,4]], there are 2 components: {0,1,2} and {3,4}. With n=3 and no edges, there are 3 components (each node isolated). With n=0, return 0.
Connected components are fundamental to graph theory. They represent clusters of related data in social networks, isolated subgraphs in communication networks, and distinct regions in geographic data.
The solution uses DFS traversal: maintain a visited array, iterate through each node, and when an unvisited node is found, start a DFS from it and increment the component count. The DFS visits all reachable nodes, marking them as visited.
Edge cases include an empty graph (return 0), a fully connected graph (1 component), and completely disconnected nodes (each node is its own component).
Example Input & Output
Two components: {0,1,2} and {3,4}
No edges: each node is its own component
Single node
3 nodes, 2 edges: one component
Chain: one component
Algorithm Flow
Solution Approach
Use DFS to visit all nodes in each component, counting components as you discover unvisited nodes.
Create an adjacency list from the edges. Maintain a visited boolean array. For each unvisited node, increment the component count and perform DFS to mark all nodes in that component as visited. Return the total count.
Time complexity is O(n + e), space complexity is O(n + e).
Best Answers
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.
