Number of Connected Components in an Undirected Graph (LeetCode 323): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Initialize
par[i] = iso every node is its own root, andrank[i] = 1to hold each tree's size. find(n1)walks parent pointers to the root, settingpar[res] = par[par[res]]along the way to flatten the path.union(n1, n2)finds both roots. If they are equal, the edge is internal to a component, so it returns 0.- Otherwise it attaches the smaller tree's root under the larger one, adds the sizes, and returns 1.
- Start with
res = nand subtract the result ofunionfor every edge. - Return
res.
Step-by-step example
n = 5, edges = [[0,1],[1,2],[3,4]]
- Start with
par = [0,1,2,3,4], all sizes 1, andres = 5. - Edge [0,1]: roots 0 and 1 differ and have equal size, so
par[0] = 1andrank[1] = 2.res = 4. - Edge [1,2]: roots are 1 and 2. Size 2 beats size 1, so
par[2] = 1andrank[1] = 3.res = 3. - Edge [3,4]: roots 3 and 4 differ with equal size, so
par[3] = 4andrank[4] = 2.res = 2. - 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 res1class Solution {
2 public int countComponents(int n, int[][] edges) {
3 int[] par = new int[n];
4 int[] rank = new int[n];
5 for (int i = 0; i < n; i++) {
6 par[i] = i;
7 rank[i] = 1;
8 }
9
10 int res = n;
11 for (int[] edge : edges) {
12 res -= union(edge[0], edge[1], par, rank);
13 }
14 return res;
15 }
16
17 private int find(int n1, int[] par) {
18 int res = n1;
19 while (res != par[res]) {
20 par[res] = par[par[res]];
21 res = par[res];
22 }
23 return res;
24 }
25
26 private int union(int n1, int n2, int[] par, int[] rank) {
27 int p1 = find(n1, par);
28 int p2 = find(n2, par);
29 if (p1 == p2) return 0;
30
31 if (rank[p1] > rank[p2]) {
32 par[p2] = p1;
33 rank[p1] += rank[p2];
34 } else {
35 par[p1] = p2;
36 rank[p2] += rank[p1];
37 }
38 return 1;
39 }
40}1class Solution {
2public:
3 int countComponents(int n, vector<vector<int>>& edges) {
4 vector<int> par(n);
5 iota(par.begin(), par.end(), 0);
6 vector<int> rank(n, 1);
7
8 int res = n;
9 for (const auto& edge : edges) {
10 res -= unionNodes(edge[0], edge[1], par, rank);
11 }
12 return res;
13 }
14
15 int find(int n1, vector<int>& par) {
16 int res = n1;
17 while (res != par[res]) {
18 par[res] = par[par[res]];
19 res = par[res];
20 }
21 return res;
22 }
23
24 int unionNodes(int n1, int n2, vector<int>& par, vector<int>& rank) {
25 int p1 = find(n1, par);
26 int p2 = find(n2, par);
27 if (p1 == p2) return 0;
28
29 if (rank[p1] > rank[p2]) {
30 par[p2] = p1;
31 rank[p1] += rank[p2];
32 } else {
33 par[p1] = p2;
34 rank[p2] += rank[p1];
35 }
36 return 1;
37 }
38};Time and space complexity
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.
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
unionmerges 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
resat n accounts for nodes with no edges, while counting only nodes seen inedgeswould 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.