Number of Connected Components

medium

Given an undirected graph with V vertices (0 .. V-1) and an edge list edges, return the number of connected components — maximal groups of vertices that are all reachable from one another. Isolated vertices count as their own component.

Hints

A component is everything reachable from one vertex — flood it.
Each unvisited vertex you start from is exactly one new component.
Union-Find alternative: start count at V and subtract one for every edge that merges two different sets.

Common doubts

When edges arrive one at a time (a stream) — it maintains the running component count in near-O(1) amortized per edge, without rebuilding a traversal.
An edge within an existing component doesn't change connectivity; only edges that join two distinct sets reduce the count.
Path compression alone already gives near-constant amortized finds here; union by rank/size makes it provably near-linear.

Interview follow-ups

Track a size array in union-find, or count nodes during each flood.
A grid is a graph whose edges connect adjacent land cells; islands are its connected components.

Fun facts

  • Union-Find with path compression + union by rank has near-constant amortized cost — the inverse-Ackermann function α grows slower than any practical log.
  • Counting components is the 'hello world' of both DFS and DSU.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: V = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
{0,1,2} and {3,4} are the two components.
Example 2
Input: V = 3, edges = []
Output: 3
Three isolated vertices are three components.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - 0 <= u, v < V - u != v

Solve this problem →