Number of Connected Components in an Undirected Graph

Union-find each edge; count distinct roots.

Medium
Time O((n + e) * alpha(n)) Space O(n)
LeetCode
3 min read
union-find graph

Problem#

Given n nodes and an edge list, return the number of connected components.

Examples#

  • n=5, edges=[[0,1],[1,2],[3,4]]2.
  • n=5, edges=[[0,1],[1,2],[2,3],[3,4]]1.

Constraints#

  • 1 <= n <= 2000.

Approach#

Union-find. Initialize n components; union both endpoints of each edge; return the number of nodes still pointing to themselves as root.

Solution#

Number of Connected Components
class Solution {
vector<int> par;
int find(int x) { return par[x] == x ? x : par[x] = find(par[x]); }
public:
int countComponents(int n, vector<vector<int>>& edges) {
par.resize(n);
iota(par.begin(), par.end(), 0);
int comps = n;
for (auto& e : edges) {
int a = find(e[0]), b = find(e[1]);
if (a != b) { par[a] = b; --comps; }
}
return comps;
}
};

Editorial#

DSU runs in near-linear time with path compression alone. The component count decreases by 1 on every successful union; starting at n and decrementing is cleaner than counting roots at the end.

Complexity#

  • Time: ~O(n + e).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.