InterviewPrepKit

Home / Coding / Graphs

Number of Connected Components in an Undirected Graph

medium Original ↗
Solving tips
  • The count equals how many times you start a fresh DFS/BFS: loop over all nodes and traverse each unvisited one, incrementing the count per new start; O(n+E).
  • Union-find is the clean alternative: start count at n, union each edge's endpoints, and decrement only on a successful merge (endpoints in different sets).
  • Build the adjacency list undirected (add both a->b and b->a), or half the graph disappears.
  • Pitfall: don't blindly decrement on every edge in union-find; a cycle edge (already-same root) must not reduce the count, and prefer BFS/union-find over deep recursion on a 2000-node chain.

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.

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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.