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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code