Code Logo

Count Connected Components

Published at25 Jul 2026
DFS Medium 1 views
Like0

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

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

Use DFS to visit all nodes in each component, counting components as you discover unvisited nodes.

function countComponents(n, edges)
  visited = array of n false values
  count = 0
  for i = 0 to n - 1
    if not visited[i]
      count = count + 1
      dfs(i)
  return count

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

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);}
    }
}