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

Medium
Depth First Search
Breadth First Search
Union Find
Graph

You have 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 maximal group of nodes that can all reach each other.

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

Intuition

One 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 is linear and perfectly fine. Union-find offers a different view that is often simpler to write and works well when edges arrive one at a time.

Start by assuming every node is its own component, so the count is n. Each edge either connects two nodes that are already in the same component, in which case nothing changes, or it joins two different components into one, in which case the count drops by exactly one. So the answer is n minus the number of edges that actually merged something.

Union-find tracks which component each node belongs to through a parent pointer to a representative root. find follows parents up to the root and, with path compression, points every visited node straight at the root. union finds both roots, and if they differ, hangs the shorter tree under the taller one using rank. Together these keep the trees almost flat, so each lookup touches only a few nodes no matter how many edges have been processed.

Approach: Union-find with path compression and union by rank

  1. Initialize parent[i] = i and rank[i] = 0 for every node.
  2. find(x) recursively finds the root and sets parent[x] to it along the way.
  3. union(x, y) finds both roots and returns False if they are the same, meaning the edge is redundant.
  4. Otherwise it attaches the lower-rank root under the higher-rank root, bumps the rank on a tie, and returns True.
  5. Start components = n and decrement it for every edge where union returns True.
  6. Return components, which now equals the number of distinct roots in the forest.

Step-by-step example

n = 5, edges = [[0,1],[1,2],[0,2],[3,4]]
  1. Start with five singleton components, so components = 5.
  2. Edge [0,1]: roots 0 and 1 differ and ranks tie, so parent[1] = 0, rank[0] = 1, and components = 4.
  3. Edge [1,2]: find(1) is 0 and find(2) is 2. Rank 1 beats rank 0, so parent[2] = 0 and components = 3.
  4. Edge [0,2]: both roots are 0, so union returns False and the count stays 3.
  5. Edge [3,4]: parent[4] = 3 and components = 2. The answer is 2: {0, 1, 2} and {3, 4}.

Code: Python, Java, C++

1class Solution:
2    def countComponents(self, n: int, edges: List[List[int]]) -> int:
3        parent = list(range(n))
4        rank = [0] * n
5
6        def find(x):
7            if parent[x] != x:
8                parent[x] = find(parent[x])
9            return parent[x]
10
11        def union(x, y):
12            px, py = find(x), find(y)
13            if px == py:
14                return False
15            if rank[px] < rank[py]:
16                px, py = py, px
17            parent[py] = px
18            if rank[px] == rank[py]:
19                rank[px] += 1
20            return True
21
22        components = n
23        for a, b in edges:
24            if union(a, b):
25                components -= 1
26
27        return components

Time and space complexity

Time

O(n + E × α(n))

Initialization is O(n). Each of the E edges does two finds, and with both path compression and union by rank each find costs amortized α(n), the inverse Ackermann function, which is at most 4 for any realistic input.

Space

O(n)

The parent and rank arrays each hold one entry per node. The recursive find can use stack space, but union by rank keeps tree depth O(log n).

Other approaches

DFS or BFS traversal (time O(n + E), space O(n + E))

Build an adjacency list, then loop over nodes and launch a traversal from each unvisited one, counting launches. Equally fast and arguably more intuitive, but needs the whole graph built first.

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

Plain parent pointers with no rank or compression. Simple, but trees can become long chains, making each find O(n) in the worst case.

Common mistakes

  • Decrementing the count for every edge instead of only for edges that join two different roots. Redundant edges inside a component would make the answer too small.
  • Comparing parent[x] values instead of find(x) results. Two nodes in the same component can have different direct parents.
  • Forgetting isolated nodes. A node with no edges is still its own component, which is why the count starts at n, not at the number of nodes seen in edges.
  • Setting parent[x] = y instead of parent[root_x] = root_y in union, which detaches x from its tree and splits components.

Frequently asked questions

How do you count connected components with union-find?

Start with n components and union the endpoints of every edge. Each union that merges two different roots reduces the count by one, and the final count is the answer.

Is DFS or union-find better for counting components?

Both are effectively linear. DFS is natural when you already have an adjacency list, while union-find shines when edges arrive as a stream or you also need to answer connectivity queries.

Why use union by rank and path compression together?

Each alone gives O(log n) amortized finds, but together they bring the cost down to the inverse Ackermann function, which is practically constant.

What is the time complexity of this solution?

O(n + E × α(n)), dominated by one pair of near-constant finds per edge, plus O(n) to set up the arrays.