Number of Connected Components in an Undirected Graph
You get n nodes labeled 0 to n−1 and a list of undirected edges (up to 2000 nodes, 5000 edges, no duplicates or self-loops). A connected component is a group of nodes that can all reach each other through edges. Count how many separate components the graph has — isolated nodes with no edges count as their own components.
Examples
- Input:
- n = 5, edges = [[0,1],[1,2],[3,4]]
- Output:
- 2
Nodes {0,1,2} form one component and {3,4} form another.
- Input:
- n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
- Output:
- 1
The chain connects all five nodes into a single component.
- Input:
- n = 3, edges = []
- Output:
- 3
With no edges, each node is its own component.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.