InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Number of Connected Components in an Undirected Graph

medium Original ↗ 00:00

Problem

You have an undirected graph with n nodes labeled 0 to n - 1. You’re given the number n and a list edges, where each edges[i] = [a, b] is an undirected edge connecting nodes a and b.

Return the number of connected components in the graph — that is, the number of maximal groups of nodes such that every node in a group is reachable from every other node in the same group, and no edge crosses between groups.

Examples

  • n = 5, edges = [[0,1],[1,2],[3,4]]2{0,1,2} form one component and {3,4} the other.
  • n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]1 — the edges chain all five nodes together.
  • n = 4, edges = []4 — with no edges, every node is its own component.

The first example has two components: {0,1,2} and {3,4}.

graph LR
  0 --- 1
  1 --- 2
  3 --- 4

Constraints

  • 1 <= n <= 2000
  • 0 <= len(edges) <= n * (n - 1) / 2
  • No self-loops and no duplicate edges; each edges[i] = [a, b] has a != b.

Think about it first

Hint 1 A component is a set of mutually reachable nodes. If you start a traversal at an unvisited node and mark everything you can reach, you've discovered exactly one whole component.
Hint 2 Loop over all nodes. Each time you find one that hasn't been visited yet, run a DFS or BFS from it (marking everything reachable) and add one to your count. The number of times you *start* a fresh traversal is the number of components.
Hint 3 There's a classic alternative that avoids building an adjacency list: union-find (disjoint-set union). Start with `n` separate sets and union the two endpoints of every edge. The number of distinct roots at the end is the component count.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug