Number of Connected Components in an Undirected Graph (LeetCode 323): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Union Find
Graph

You are given n nodes labeled 0 to n - 1 and a list of undirected edges. Return how many connected components the graph has, where a component is a group of nodes that can all reach each other.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

One natural way is to build an adjacency list and run DFS or BFS from every unvisited node, counting how many times you start a new search. That works in O(n + E) and is a fine answer. The reference solution takes a different view that avoids building the graph at all.

Start by assuming every node is its own component, so the count is n. Now process edges one at a time. An edge between two nodes that are already in the same component changes nothing. An edge between two different components fuses them into one, so the count drops by exactly one. The answer is n minus the number of edges that actually joined two separate components.

Union-find is built for exactly that question. Each component is a tree identified by its root, find walks up to the root, and union links one root under the other. Two optimizations keep the trees shallow. Path halving inside find makes each node point to its grandparent while walking up, and union by size attaches the smaller tree under the larger one. Together they make each operation run in near-constant amortized time.

Approach: Union-find with path halving and union by size

  1. Initialize par[i] = i so every node is its own root, and rank[i] = 1 to hold each tree's size.
  2. find(n1) walks parent pointers to the root, setting par[res] = par[par[res]] along the way to flatten the path.
  3. union(n1, n2) finds both roots. If they are equal, the edge is internal to a component, so it returns 0.
  4. Otherwise it attaches the smaller tree's root under the larger one, adds the sizes, and returns 1.
  5. Start with res = n and subtract the result of union for every edge.
  6. Return res.

Step-by-step example

n = 5, edges = [[0,1],[1,2],[3,4]]
  1. Start with par = [0,1,2,3,4], all sizes 1, and res = 5.
  2. Edge [0,1]: roots 0 and 1 differ and have equal size, so par[0] = 1 and rank[1] = 2. res = 4.
  3. Edge [1,2]: roots are 1 and 2. Size 2 beats size 1, so par[2] = 1 and rank[1] = 3. res = 3.
  4. Edge [3,4]: roots 3 and 4 differ with equal size, so par[3] = 4 and rank[4] = 2. res = 2.
  5. Return 2: the components are {0,1,2} and {3,4}.

Code: Python, Java, C++

1class Solution:
2    def countComponents(self, n: int, edges: List[List[int]]) -> int:
3        par = [i for i in range(n)]
4        rank = [1] * n
5        
6        def find(n1):
7            res = n1
8            while res != par[res]:
9                par[res] = par[par[res]]
10                res = par[res]
11            return res
12            
13        def union(n1, n2):
14            p1, p2 = find(n1), find(n2)
15            if p1 == p2:
16                return 0
17            
18            if rank[p1] > rank[p2]:
19                par[p2] = p1
20                rank[p1] += rank[p2]
21            else:
22                par[p1] = p2
23                rank[p2] += rank[p1]
24            return 1
25            
26        res = n
27        for n1, n2 in edges:
28            res -= union(n1, n2)
29        return res

Time and space complexity

Time

O(n + E × α(n))

Initializing the arrays is O(n). Each of the E edges does two finds and a union, which with path compression and union by size cost O(α(n)) amortized, where α is the inverse Ackermann function and is at most 4 in practice.

Space

O(n)

The par and rank arrays each hold n entries. No adjacency list is built.

Other approaches

DFS or BFS over an adjacency list (time O(n + E), space O(n + E))

Build adjacency lists, then loop over nodes and launch a traversal from each unvisited one, counting launches. It is equally fast and very intuitive, but needs O(n + E) memory for the graph and recursion depth can be a concern for DFS.

Union-find without optimizations (time O(n × E), space O(n))

The same counting idea with a plain find that just walks to the root. Trees can degrade into long chains, so each operation can cost O(n) in the worst case.

Common mistakes

  • Decrementing the count for every edge instead of only when union merges two different roots, which undercounts when the graph has cycles.
  • Comparing the nodes themselves instead of their roots in union. Two nodes can be different yet already connected.
  • Forgetting isolated nodes. Starting res at n accounts for nodes with no edges, while counting only nodes seen in edges would miss them.
  • Mixing up the size update so the new root does not receive the merged size, which weakens union by size over time.

Frequently asked questions

Union-find or DFS for counting connected components?

Both are effectively linear. DFS is the most direct when you already have an adjacency list. Union-find is handy when edges arrive one at a time or you want to avoid building the graph, and it extends easily to dynamic connectivity questions.

What does path compression do?

While walking up to the root, it re-points nodes closer to the root, here to their grandparent. Later finds on those nodes take fewer steps, which keeps trees nearly flat.

Why does each successful union reduce the count by one?

A successful union joins two components that were separate, turning two into one. An edge whose endpoints already share a root lies inside a component and leaves the count unchanged.