Start learning free

LESSON 278 OF 314 · GRAPHS

Connected Components in C++: Union-Find with Path Halving

Practice O((n + e)·α(n)) Read the full explanation

You get an undirected graph with n nodes, labeled 0 to n - 1. Its edges come as a vector edges. Each edges[i] = [ai, bi] joins nodes ai and bi.

Return how many connected components the graph has.

A connected component is a group of nodes linked by edges. From any node in the group, you can reach every other one. No edge links two different groups. A node with no edges is a component by itself.

 

Example 1:

Input: n = 6, edges = [[0, 3], [3, 5], [1, 4]]
Output: 3
Explanation: Nodes 0, 3 and 5 are linked.
Nodes 1 and 4 are linked.
Node 2 has no edges at all.
    0 - 3 - 5      1 - 4      2

Example 2:

Input: n = 4, edges = [[2, 0], [0, 1], [1, 2], [1, 3]]
Output: 1
Explanation: All four nodes are linked.
The edge 1 - 2 adds nothing new.
Nodes 1 and 2 are already linked through 0.
    2 - 0
     \ /
      1 - 3

Example 3:

Input: n = 3, edges = []
Output: 3
Explanation: With no edges, each node is a component on its own.

 

Constraints:

  • 1 to 100,000 nodes.
  • 0 to 100,000 edges.
  • Each edge joins two different nodes.
  • Every node in edges is from 0 to n - 1.
  • No edge is listed twice.

Note:

Your algorithm should run in O((n + e)·α(n)) time, nearly O(n + e), where e is the number of edges, and use O(n) extra space.

The tutorial uses union-find, also called disjoint sets. Every node starts as a group of its own, so there are n components. Each edge merges the groups of its two nodes, unless they are already in the same group, and every merge leaves one component fewer. A group is kept as a tree in which each node points to its parent, and the tree's root names the group: two nodes are in the same group exactly when they lead to the same root. Two tricks keep the trees flat: path halving (on the way up to the root, point each node to its grandparent) and union by size (hang the root of the smaller tree under the root of the larger one). With both, finding a root or merging two groups costs O(α(n)) on average, where α is the inverse Ackermann function, which grows so slowly that it stays below 5 for any n a computer can hold.

A DFS or BFS from every node that isn't visited yet, as in Number of Islands, also counts the components in O(n + e); on a graph this big, use a BFS or a DFS with its own stack, since a recursive DFS down a path of 105 nodes can run out of call stack. Union-find is worth knowing because it keeps working while the edges arrive one at a time: after each new edge it can still tell, almost at once, whether two nodes are connected, without searching the graph again.

STEP 1 OF 19
    Ctrl + Enter to check

    C++ · GRAPHS

    Number Of Connected Components In An Undirected Graph in C++, explained

    Problem overview

    The method countComponents receives n, the number of nodes (numbered 0 to n - 1), and a vector<vector<int>> named edges. Each edge [a, b] joins two nodes in both directions. It returns how many connected components the graph has: groups of nodes that can reach one another, with no edge leaving the group. A node with no edges counts as a component of its own.

    For n = 5 and edges = [[0, 1], [1, 2], [3, 4]], nodes 0, 1 and 2 form one group and nodes 3 and 4 another, so the answer is 2. For n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]] the answer is 3: the cycle 0-1-2, the pair 3-4, and the lonely node 5. The edge 2-0 joins nodes that were already connected through node 1, so it changes nothing.

    The statement asks for nearly linear time, O((n + e)·α(n)) with e edges, and O(n) extra space.

    Approach: union-find

    A search (DFS or BFS) from every unvisited node also counts components in O(n + e). This lesson uses union-find instead, which handles edges one at a time and always knows which nodes are connected.

    The idea is to start with n components, one per node, and let every edge try to merge two of them. Each group is stored as a tree where every node points to a parent. The root, the one node that is its own parent, names the group. Two nodes are in the same group exactly when they lead to the same root.

    For each edge, find the two roots. If they differ, the edge joins two groups: merge them and subtract one from the count. If they are equal, the edge closes a cycle and the count stays.

    Two tricks keep the trees shallow, so that finding a root costs O(α(n)) on average, where α is the inverse Ackermann function and stays below 5 for any realistic n:

    • Union by size: hang the root of the smaller tree under the root of the larger one.
    • Path halving: while walking up to the root, point each node at its grandparent.

    Here is the first example traced with the lesson's code, printing parent and size after each edge:

    edge 0-1 parent=0 0 2 3 4 size=2 1 1 1 1 components=4
    edge 1-2 parent=0 0 0 3 4 size=3 1 1 1 1 components=3
    edge 3-4 parent=0 0 0 3 3 size=3 1 1 2 1 components=2
    

    Only the sizes of roots matter: node 1's entry stays 1 after it stops being a root.

    Step by step

    1. Create parent with one slot per node.
    2. Create size, filled with 1: every node starts as a group of one. Only roots keep a meaningful size.
    3. Loop over the nodes and set parent[i] = i, making each node the root of its own group.
    4. Start components at n, since no edge has been used yet.
    5. Loop over the edges by reference with auto&, so no edge is copied.
    6. Find both roots with the find helper, written last.
    7. If the roots differ, make rootA the root of the larger group by swapping when size[rootA] < size[rootB].
    8. Attach rootB under rootA and add its size to rootA's.
    9. Decrease components: two groups became one.
    10. Return components.
    11. Write find: it takes parent by reference, because it changes it, and loops while parent[x] != x. In the loop it points x at its grandparent, then moves x to that node. It returns the root.

    The solution in C++

    class Solution {
    public:
        int countComponents(int n, vector<vector<int>>& edges) {
            vector<int> parent(n);
            vector<int> size(n, 1);
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
            int components = n;
            for (auto& edge : edges) {
                int rootA = find(parent, edge[0]);
                int rootB = find(parent, edge[1]);
                if (rootA != rootB) {
                    if (size[rootA] < size[rootB]) {
                        swap(rootA, rootB);
                    }
                    parent[rootB] = rootA;
                    size[rootA] += size[rootB];
                    components--;
                }
            }
            return components;
        }
    
        int find(vector<int>& parent, int x) {
            while (parent[x] != x) {
                parent[x] = parent[parent[x]];
                x = parent[x];
            }
            return x;
        }
    };
    

    C++ details worth knowing:

    • Constructors. vector<int> parent(n) makes n zeros, and vector<int> size(n, 1) makes n ones. Parentheses give a size here; braces would make a list of values.
    • Reference parameter. vector<int>& parent lets find change the caller's vector. Without the &, each call would copy all n elements and the shortening would be lost.
    • x is a copy. The int x parameter is passed by value, so moving it up the tree doesn't change the caller's variable.
    • Order of members. countComponents calls find before it appears in the class. That is fine: inside a class, member function bodies can use members declared later.
    • Loop, not recursion. find uses a while loop. A recursive version on a long chain could use a lot of call stack. With n = 100000 and the edges [i, i + 1] forming one path, the lesson's code returns 1.
    • swap exchanges the two local ints, which only reorders which root is called rootA.

    Complexity

    Time: O((n + e)·α(n)). Setting up is O(n). Each of the e edges makes two find calls, and with union by size and path halving each call costs O(α(n)) on average. Union by size alone already keeps every path within log2(n) steps.

    Space: O(n). The vectors parent and size hold one int per node.

    Edge cases and common mistakes

    • No edges. With n = 4 and no edges the loop never runs and the answer is 4.
    • Edges inside a group. A cycle edge has equal roots and must not decrease components. Subtracting once per edge gives wrong answers.
    • Comparing the nodes instead of the roots. Nodes 0 and 2 in [[0, 1], [1, 2]] are connected although no edge joins them directly. Only roots tell.
    • Forgetting the & in find's signature. The code still compiles, but it copies the vector on every call, which is far too slow for 100,000 nodes.
    • Merging the wrong things. Set parent[rootB], not parent[edge[1]]. Attaching a non-root node would cut it off from its own group.

    Testing

    • n = 5, edges = [[0, 1], [1, 2], [3, 4]] gives 2.
    • n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4]] gives 1.
    • n = 6, edges = [[0, 1], [1, 2], [2, 0], [3, 4]] gives 3.
    • n = 1, no edges gives 1, and n = 4, no edges gives 4.
    • n = 4, edges = [[0, 1], [2, 3], [1, 2]] gives 1: the last edge merges two groups of two.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free