Number of Connected Components in an Undirected Graph

Pattern: Connected components and islands

medium

Start with every vertex in its own group. For each edge, join the two ends' groups with union-find; every successful join reduces the count by one. Alternatively, count how many searches you need to visit everything.

The problem

Given n vertices and undirected edges, return the number of connected components. Vertices are numbered from 0 and each edge is given as [u, v]. LeetCode's version is premium.

Think first

  • How many components are there with no edges?
  • What can one edge do to the count?
  • When does an edge change nothing?

Hints

    Brute force, and why it fails

    Start a DFS from each unvisited vertex and count them: also O(V + E).

    The key insight

    Each edge either merges two groups or is redundant, so the count is n minus the number of merges.

    Dry run

    groups5

    n = 5, edges 0-1, 1-2, 3-4. Five groups at first.

    Step 1 of 3

    The plan

    parent[i] = i; count = n
    for (u, v): if find(u) != find(v): union; count -= 1
    

    Complexity

    Time
    O(V + E α(V))
    Space
    O(V)

    Almost constant time per edge.

    Edge cases

    • A single vertex with no edges.
    • A graph in several pieces.
    • Many edges at one vertex.
    I've built my logic, show the code

    Java

    class Solution {
        private int[] parent;
    
        public int countComponents(int n, int[][] edges) {
            parent = new int[n];
            for (int i = 0; i < n; i++) parent[i] = i;
            int count = n;                          // every vertex starts alone
            for (int[] e : edges) {
                int a = find(e[0]), b = find(e[1]);
                if (a != b) { parent[a] = b; count--; }   // two groups join into one
            }
            return count;
        }
    
        private int find(int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    }

    C++

    class Solution {
    public:
        vector<int> parent;
    
        int countComponents(int n, vector<vector<int>>& edges) {
            parent.resize(n);
            for (int i = 0; i < n; i++) parent[i] = i;
            int count = n;                          // every vertex starts alone
            for (const vector<int>& e : edges) {
                int a = find(e[0]), b = find(e[1]);
                if (a != b) { parent[a] = b; count--; }   // two groups join into one
            }
            return count;
        }
    
        int find(int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    };

    Python

    class Solution:
        def countComponents(self, n: int, edges: list[list[int]]) -> int:
            parent = list(range(n))
    
            def find(x):
                while parent[x] != x:
                    parent[x] = parent[parent[x]]
                    x = parent[x]
                return x
    
            count = n                               # every vertex starts alone
            for u, v in edges:
                a, b = find(u), find(v)
                if a != b:
                    parent[a] = b                   # two groups join into one
                    count -= 1
            return count

    Common mistakes

    • Counting edges.
    • Forgetting isolated vertices.

    Similar problems