Article start
DSA Course: Interview Patterns and Problem Solving
Module 7: Graphs

Connected Components: Adjacency DFS Pattern

Build an adjacency list and count how many DFS starts are needed.

May 29, 2026·26

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.

InputOutputWhy
n = 5, edges = [[0,1],[1,2],[3,4]]2Nodes 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 components

Sample Dry Run

StepStateResult
Build graph0 connects 1, 1 connects 0 and 2, 3 connects 4Adjacency is ready
Start at 0DFS visits 0,1,2components = 1
Node 3 unseenDFS visits 3,4components = 2
Finish scanAll nodes seenreturn 2

Complexity

MeasureValueReason
TimeO(n + e)Every node and edge is processed through the adjacency list.
SpaceO(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.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.