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: Find Separate Groups in GraphInput: n=5, edges=[[0,1],[1,2],[3,4]]01234Component 1: {0, 1, 2}Component 2: {3, 4}Graph Traversal Process:1. Start DFS from node 0 → visits 0,1,2 → Component count = 12. Start DFS from node 3 → visits 3,4 → Component count = 23. All nodes visited → Final answer = 2Output: 2 Connected Components
Understanding the Visualization
1
Input Graph
Graph with n=5 nodes and edges [[0,1],[1,2],[3,4]]
2
Find Components
Use graph traversal to group connected nodes
3
Count Result
Return number of separate components found
Key Takeaway
🎯 Key Insight: Use graph traversal to group nodes - each traversal starting point represents a new connected component
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