ExamAdda Logo

Build an adjacency list and start DFS/BFS from node 0.

Easy

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.

  1. Build an adjacency list.
  2. Keep a visited array.
  3. Traverse every node.
  4. Whenever we find an unvisited node, it represents a new connected component.
  5. Run DFS/BFS from that node and mark all reachable nodes as visited.
  6. 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

1 <= n <= 2000
1 <= edges.length <= 5000
0 <= ai
bi < n
ai != bi
There are no duplicate edges.

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

ExamAdda Technical Review Team

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.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output