Start learning free

LESSON 561 OF 671 · GRAPHS

Connected Components in JavaScript: 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 an array 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 17
    Ctrl + Enter to check

    JAVASCRIPT · GRAPHS

    Number Of Connected Components In An Undirected Graph in JavaScript, explained

    Problem overview

    The method countComponents(n, edges) receives the number of nodes n, numbered 0 to n - 1, and an array edges of pairs. Each pair [a, b] is an undirected edge between two nodes. A connected component is a group of nodes that can reach one another through edges, with no edge leaving the group. The method returns how many such groups the graph has. A node with no edges counts as a component of its own.

    With n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]], nodes 0, 1 and 2 form one group, nodes 3 and 4 a second one, and node 5, which has no edges, a third. The answer is 3. The edge [2, 0] changes nothing, because 0 and 2 are already connected through node 1.

    The statement asks for about O(n + e) time (precisely O((n + e)·α(n))) and O(n) extra space, with up to 100,000 nodes and 100,000 edges.

    Approach: start with n groups and merge

    A depth-first or breadth-first search from every unvisited node also counts components in O(n + e), and for large inputs it needs an explicit stack or queue, since a recursive search down a path of 100,000 nodes can exhaust the call stack. This lesson uses union-find (disjoint sets), which looks at the edges one by one and never builds an adjacency list.

    The idea is a counting argument. At the start, with no edges used, every node is its own group, so there are n components. An edge between two nodes in different groups merges them, and the number of components drops by exactly one. An edge between two nodes that are already in the same group changes nothing. So the answer is n minus the number of edges that actually merged two groups.

    To tell the cases apart quickly, each group is stored as a tree in an array: parent[i] is the parent of node i, and the root, the one node that is its own parent, names the group. Two nodes share a group exactly when walking up from each reaches the same root. Two tricks keep the trees shallow:

    • Union by size. When merging, the root of the smaller tree goes under the root of the larger one. A node only gets deeper when its group at least doubles, so no path is longer than log2(n) steps.
    • Path halving. While walking up to the root, each node is pointed at its grandparent. Later walks from the same nodes are shorter.

    Together they make each find or merge cost O(α(n)) on average, where α is the inverse Ackermann function, which stays below 5 for any input size a computer can hold. In practice that is constant.

    Here is the method on the example. After each edge, the trace shows the arrays and the component count:

    edge [0,1]: parent [0,0,2,3,4,5]  size [2,1,1,1,1,1]  components 5
    edge [1,2]: parent [0,0,0,3,4,5]  size [3,1,1,1,1,1]  components 4
    edge [2,0]: parent [0,0,0,3,4,5]  size [3,1,1,1,1,1]  components 4
    edge [3,4]: parent [0,0,0,3,3,5]  size [3,1,1,2,1,1]  components 3
    

    The third edge finds the same root, 0, for both of its nodes, so nothing changes and the cycle is ignored.

    Step by step

    1. Create parent. Array.from({length: n}, (_, i) => i) builds an array where parent[i] is i: every node starts as the root of a group of one. The callback gets the value (unused, hence _) and the index.
    2. Create size, filled with 1. Only the entries of roots are kept current. They decide which tree goes under which.
    3. Start components at n with let, because it goes down with every merge.
    4. Loop over edges with for...of. Each edge either merges two groups or lies inside one.
    5. Find the roots of both endpoints with this.find, into rootA and rootB. They use let because the next step may swap them. The helper is written last.
    6. Compare the roots. If they are equal, the edge closes a cycle and the loop moves on. If they differ, the groups must be merged.
    7. Make rootA the larger root. If size[rootA] < size[rootB], swap the two variables with a destructuring assignment.
    8. Hang the smaller tree under the larger: parent[rootB] = rootA.
    9. Update the size: size[rootA] += size[rootB]. The value of size[rootB] is never read again, because rootB is no longer a root.
    10. Decrement components. Two components became one.
    11. Return components after the loop.
    12. Write find(parent, x). It is a method of the same class, called through this. The array is passed by reference, so changes made inside find are visible in countComponents.
    13. Loop while parent[x] !== x. Only a root is its own parent. A loop needs no call stack, however long the walk.
    14. Point x at its grandparent with parent[x] = parent[parent[x]]. This is path halving.
    15. Move up with x = parent[x]. That is the old grandparent, so each turn climbs two levels.
    16. Return x, the root.

    The solution in JavaScript

    class Solution {
        countComponents(n, edges) {
            const parent = Array.from({length: n}, (_, i) => i);
            const size = new Array(n).fill(1);
            let components = n;
            for (const edge of edges) {
                let rootA = this.find(parent, edge[0]);
                let rootB = this.find(parent, edge[1]);
                if (rootA !== rootB) {
                    if (size[rootA] < size[rootB]) {
                        [rootA, rootB] = [rootB, rootA];
                    }
                    parent[rootB] = rootA;
                    size[rootA] += size[rootB];
                    components--;
                }
            }
            return components;
        }
    
        find(parent, x) {
            while (parent[x] !== x) {
                parent[x] = parent[parent[x]];
                x = parent[x];
            }
            return x;
        }
    }
    

    A few JavaScript details are worth a closer look:

    • Swapping without a temporary. [rootA, rootB] = [rootB, rootA] builds an array of the two current values and unpacks it back in the other order. The previous line ends in {, so the statement starting with [ is not glued onto an earlier expression. If you leave semicolons out of your own code, a line that starts with [ needs care.
    • Array.from versus fill. new Array(n).fill(1) is right for numbers. For arrays of arrays, new Array(n).fill([]) would put the same array at every position, so pushing into one would change them all. Array.from with a callback creates a fresh value per index.
    • Parameters are reassignable. The loop in find changes x, the local copy of the argument. The caller's variable is untouched, but the parent array, being an object, is shared.
    • === and !==. They compare without type conversion. Node numbers are always numbers here, so they behave as expected.

    Complexity

    Time: O((n + e)·α(n)). Building the arrays costs O(n). The loop runs once per edge, and each iteration makes two find calls and at most one merge, each costing O(α(n)) on average. For practical sizes this is the same as O(n + e).

    Space: O(n). The parent and size arrays hold one number per node. Nothing grows with the number of edges, and there is no recursion.

    Edge cases and common mistakes

    • No edges. With n = 4 and edges = [], the loop never runs and the method returns 4. With n = 1 it returns 1.
    • Isolated nodes. A node that appears in no edge is still a component. Counting only the groups seen in the edges would miss it. Starting from n handles this automatically.
    • Cycles. An edge between nodes that already share a root must not decrement components. Decrementing once per edge would give 1 instead of 3 for the example above.
    • Comparing nodes instead of roots. Checking edge[0] !== edge[1] says nothing about whether the groups differ. Always compare the roots.
    • Merging into the wrong root. Setting parent[edge[1]] = edge[0] without finding the roots first cuts a node out of its tree and loses part of the group.
    • Updating size for non-roots. Only the root's entry matters, so add the sizes of the two roots, not of the original nodes.
    • Deep recursion. A recursive find or depth-first search over a long path can overflow the call stack. The while loop in find avoids that.

    Testing

    These inputs were run against the solution:

    • 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 = 4, edges = [[0, 1], [2, 3], [1, 2]] gives 1.
    • n = 5, edges = [[0, 1], [2, 3]] gives 3.
    • n = 4, edges = [] gives 4.
    • A path through 100,000 nodes ([0, 1], [1, 2], and so on) gives 1 without a stack overflow.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free