</>

323. Number of Connected Components in an Undirected Graph

Medium NeetCode 150
Graphs Time O((n + e) * alpha(n)) Space O(n)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Graphs
Time
O((n + e) * alpha(n))
Space
O(n)

Standard Solution (C++)

SummaryCount how many separate connected groups exist among n labeled nodes given a list of undirected edges.

Approach

Union-Find (disjoint set union).

  • Start with n singleton components.
  • For each edge, union the two endpoints; every successful union (joining two distinct roots) reduces the component count by one.
  • Use path compression and union by rank for near-constant amortized operations.
class Solution {
    vector<int> parent, rnk;
    int find(int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }
public:
    int countComponents(int n, vector<vector<int>>& edges) {
        parent.resize(n);
        rnk.assign(n, 0);
        for (int i = 0; i < n; ++i) parent[i] = i;
        int count = n;
        for (auto& e : edges) {
            int a = find(e[0]), b = find(e[1]);
            if (a == b) continue;
            if (rnk[a] < rnk[b]) swap(a, b);
            parent[b] = a;
            if (rnk[a] == rnk[b]) rnk[a]++;
            count--;
        }
        return count;
    }
};
Time O((n + e) * alpha(n)) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern