Blind 75 · Graphs

Number of Connected Components in an Undirected Graph

Medium

Watch the walkthrough (5:37)

Problem

You are given n nodes labeled 0 to n - 1 and a list of undirected edges.
Return how many connected components the graph has. A node with no edges is its own component.

Examples

Example 1:
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2

Example 2:
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1

Example 3:
Input: n = 4, edges = []
Output: 4

Example 4:
Input: n = 6, edges = [[0,1],[2,3],[4,5]]
Output: 3

Constraints

1 <= n <= 2000
0 <= edges.length <= 5000
No self-loops or duplicate edges.

Prerequisites

Graph traversal — DFS and BFS, and a visited set as the thing that makes both terminate.
Union-find for connectivity questions; topological order for dependency ones.

How to think about it

1. Count Down From n Groups Optimal

Intuition

Before any edge is read, every node is a group of its own: n groups. An edge whose two ends have different roots joins two groups into one, which leaves one group fewer. An edge whose two ends already share a root is inside a group, and changes nothing. So start the count at n and take one off for every edge that joins two groups; the count left is the number of connected components.

Algorithm

1. Start parent with every node as its own root, and the count at n.
2. For each edge, find the root of each end, rootA and rootB. find(x) climbs while x is not its own root, pointing x at its grandparent on each step (path halving), and returns the root.
3. If the roots differ, point rootA at rootB and take one off the count.
4. Return the count.

Time & Space

Time O(n + m log n) for n nodes and m edges: path halving with plain linking keeps each find O(log n) on average. Space O(n).

2. Union-Find, Counting Merges Optimal

Intuition

Start by assuming nothing is connected: n nodes, n components. Every edge that joins two DIFFERENT groups reduces the count by one; an edge inside a group changes nothing. The count falls out of the merges without any traversal at all.

Algorithm

1. Every node is its own parent; components equals n.
2. For each edge, find both roots.
3. Different roots: union them and decrement the count.
4. The remaining count is the answer.

Time & Space

Time near O(edges) with path compression. Space O(n). A DFS counting fresh starts is the same answer by another road.