Number of Connected Components in an Undirected Graph (LeetCode 323): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Initialize
parent[i] = iandrank[i] = 0for every node. find(x)recursively finds the root and setsparent[x]to it along the way.union(x, y)finds both roots and returnsFalseif they are the same, meaning the edge is redundant.- Otherwise it attaches the lower-rank root under the higher-rank root, bumps the rank on a tie, and returns
True. - Start
components = nand decrement it for every edge whereunionreturnsTrue. - 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]]
- Start with five singleton components, so
components = 5. - Edge
[0,1]: roots 0 and 1 differ and ranks tie, soparent[1] = 0,rank[0] = 1, andcomponents = 4. - Edge
[1,2]:find(1)is 0 andfind(2)is 2. Rank 1 beats rank 0, soparent[2] = 0andcomponents = 3. - Edge
[0,2]: both roots are 0, sounionreturnsFalseand the count stays 3. - Edge
[3,4]:parent[4] = 3andcomponents = 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 components1class Solution {
2 int[] parent, rank;
3
4 public int countComponents(int n, int[][] edges) {
5 parent = new int[n];
6 rank = new int[n];
7 for (int i = 0; i < n; i++) parent[i] = i;
8
9 int components = n;
10 for (int[] edge : edges) {
11 if (union(edge[0], edge[1])) components--;
12 }
13 return components;
14 }
15
16 int find(int x) {
17 if (parent[x] != x) parent[x] = find(parent[x]);
18 return parent[x];
19 }
20
21 boolean union(int x, int y) {
22 int px = find(x), py = find(y);
23 if (px == py) return false;
24 if (rank[px] < rank[py]) { int t = px; px = py; py = t; }
25 parent[py] = px;
26 if (rank[px] == rank[py]) rank[px]++;
27 return true;
28 }
29}1class Solution {
2public:
3 vector<int> parent, rnk;
4
5 int countComponents(int n, vector<vector<int>>& edges) {
6 parent.resize(n);
7 rnk.resize(n, 0);
8 for (int i = 0; i < n; i++) parent[i] = i;
9
10 int components = n;
11 for (auto& edge : edges) {
12 if (unite(edge[0], edge[1])) components--;
13 }
14 return components;
15 }
16
17 int find(int x) {
18 if (parent[x] != x) parent[x] = find(parent[x]);
19 return parent[x];
20 }
21
22 bool unite(int x, int y) {
23 int px = find(x), py = find(y);
24 if (px == py) return false;
25 if (rnk[px] < rnk[py]) swap(px, py);
26 parent[py] = px;
27 if (rnk[px] == rnk[py]) rnk[px]++;
28 return true;
29 }
30};Time and space complexity
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.
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 offind(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] = yinstead ofparent[root_x] = root_yin union, which detachesxfrom 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.