Build an adjacency list and start DFS/BFS from node 0.
You are given n nodes labeled from 0 to n - 1 and an array of undirected edges.
Return the number of connected components in the graph.
A connected component is a group of nodes where every node is reachable from every other node in that group.
Example
n = 5
edges =
0 - 1
1 - 2
3 - 4
The graph is:
0 --- 1 --- 2
3 --- 4
There are 2 connected components:
Component 1 → {0, 1, 2}
Component 2 → {3, 4}
Answer:
2
Main Idea
Use DFS or BFS.
- Build an adjacency list.
- Keep a visited array.
- Traverse every node.
- Whenever we find an unvisited node, it represents a new connected component.
- Run DFS/BFS from that node and mark all reachable nodes as visited.
- Increment the component count.
Important
If a node is already visited, it belongs to a component we have already counted.
Example 1
Input
5 3 0 1 1 2 3 4
Output
2
Explanation
The graph contains:
0 --- 1 --- 2
3 --- 4
So there are two connected components:
{0, 1, 2}
{3, 4}
Therefore, the answer is:
2
Example 2
Input
5 0
Output
5
Explanation
There are no edges.
Therefore, every node is an independent component:
{0}
{1}
{2}
{3}
{4}
So the number of connected components is:
5
Constraints
Hints:
Hint 1
Think about what happens when you start DFS from an unvisited node.
Hint 2
Every time you start DFS from an unvisited node, you have discovered one new connected component.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 16, 2026
Last updated
Aug 16, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output