Problem
You get n nodes with the numbers 0 to n - 1. You also get a list edges of undirected edges. Each item [a, b] is an edge between node a and node b.
A connected component is a group of nodes with a path between each pair of them. No edge joins a node in the group to a node outside the group. A node with no edges is a connected component by itself.
Return the number of connected components.
Example 1
- Input:
- n = 6, edges = [[0,1],[1,2],[3,4]]
- Output:
- 3
- Explanation:
- The components are the nodes 0, 1 and 2, the nodes 3 and 4, and node 5 alone.
Example 2
- Input:
- n = 4, edges = [[0,1],[1,2],[2,3],[0,3]]
- Output:
- 1
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
- edges[i].length == 2
- 0 <= a, b < n
- a != b
- No edge occurs two times
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 2 records
Amazon
Leetcode 323. Number of Connected Components in an Undirected Graph
Reported Jun 9, 2025 · 1 source report
SENIOR
Source snapshot: Nov 12, 2026
View sourceUber
Leetcode 323. Number of Connected Components in an Undirected Graph
Reported Apr 13, 2026 · 1 source report
JUNIOR
Source snapshot: Nov 12, 2026
View source