Learning Outcome
After this lesson, you should be able to build an adjacency list, mark visited nodes, and count disconnected graph groups.
Problem Statement
Given n nodes labeled from 0 to n
- 1 and undirected edges, return the number of connected components.
| Input | Output | Why |
|---|---|---|
n = 5, edges = [[0,1],[1,2],[3,4]] | 2 | Nodes 0,1,2 form one group and nodes 3,4 form another group. |
Brute Force Approach
For every node, scan the whole edge list to discover neighbors. This repeats work and makes traversal harder to reason about.
Optimized Approach
Build the adjacency list once. For each unseen node, start DFS and mark its whole component.
Exact Pseudocode
build adjacency list from edges
seen = array of false
components = 0
for node from 0 to n - 1:
if seen[node] is false:
components += 1
dfs(node)
return components
dfs(node):
mark node as seen
for neighbor in adj[node]:
if seen[neighbor] is false:
dfs(neighbor)
Reference Code
class Solution:
def countComponents(self, n, edges):
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
seen = [False] * n
def dfs(node):
seen[node] = True
for nei in adj[node]:
if not seen[nei]:
dfs(nei)
components = 0
for node in range(n):
if not seen[node]:
components += 1
dfs(node)
return componentsSample Dry Run
| Step | State | Result |
|---|---|---|
| Build graph | 0 connects 1, 1 connects 0 and 2, 3 connects 4 | Adjacency is ready |
| Start at 0 | DFS visits 0,1,2 | components = 1 |
| Node 3 unseen | DFS visits 3,4 | components = 2 |
| Finish scan | All nodes seen | return 2 |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n + e) | Every node and edge is processed through the adjacency list. |
| Space | O(n + e) | Adjacency, seen array, and recursion stack take linear space. |
Edge Cases
- Isolated nodes count as their own components.
- Repeated edges should not start new components.
- Empty edge list with n nodes returns n.
Interview Checklist
- Build adjacency for both directions.
- Mark a node before visiting its neighbors.
- Increment the answer only when starting from an unseen node.
FAQs
Why not scan edges inside DFS?
It repeats the same neighbor discovery many times. An adjacency list pays that cost once.
What is the core pattern?
Graph DFS with a visited set.
Does an isolated node count?
Yes. It is a connected component of size one.