Number of Connected Components in an Undirected Graph - Problem

You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.

Return the number of connected components in the graph.

A connected component is a maximal set of vertices such that for every pair of vertices u and v, there is a path connecting them.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
💡 Note: There are 2 connected components: {0,1,2} and {3,4}. Node 0 connects to 1, which connects to 2. Separately, node 3 connects to 4.
Example 2 — No Edges
$ Input: n = 5, edges = []
Output: 5
💡 Note: With no edges, each node forms its own connected component: {0}, {1}, {2}, {3}, {4}.
Example 3 — Fully Connected
$ Input: n = 3, edges = [[0,1],[1,2],[0,2]]
Output: 1
💡 Note: All nodes are connected to each other, forming one connected component: {0,1,2}.

Constraints

  • 1 ≤ n ≤ 2000
  • 1 ≤ edges.length ≤ 5000
  • edges[i].length == 2
  • 0 ≤ ai ≤ bi < n
  • ai != bi
  • There are no repeated edges

Visualization

Tap to expand
Connected Components in Undirected Graph INPUT Graph with n=5 nodes 0 1 2 3 4 Component 1 Component 2 n = 5 edges = [ [0,1], [1,2], [3,4] ] ALGORITHM STEPS 1 Build Adjacency List Create graph[i] for each node 2 Initialize visited[] array Track explored nodes 3 Iterative DFS with Stack For each unvisited node 4 Count Components Increment for each new DFS DFS Stack Trace 0 1 2 DFS 1: visits 0,1,2 3 4 DFS 2: visits 3,4 FINAL RESULT Components Found: Component 1 0 1 2 Component 2 3 4 OUTPUT 2 OK - 2 components verified correctly Key Insight: Iterative DFS uses an explicit stack instead of recursion, avoiding stack overflow for large graphs. Each time we start a new DFS from an unvisited node, we've found a new connected component. Time: O(V + E) | Space: O(V) for visited array and stack TutorialsPoint - Number of Connected Components in an Undirected Graph | Optimized DFS with Iterative Stack
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
185.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen