Start learning free

LESSON 278 OF 314 · GRAPHS

Connected Components in TypeScript: Union-Find

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

    TYPESCRIPT · GRAPHS

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

    Problem overview

    The method countComponents receives n, the number of nodes (numbered 0 to n - 1), and edges, an array of [a, b] pairs that each join two nodes. It returns how many connected components the graph has. A component is a group of nodes that can reach each other by following edges, and a node with no edges counts as a component of its own.

    Take n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]]. Nodes 0, 1 and 2 form a cycle, nodes 3 and 4 are joined by one edge, and node 5 stands alone. That makes three components, and the method returns 3.

    The constraints allow up to 100,000 nodes and 100,000 edges, and the note asks for nearly O(n + e) time with O(n) extra space.

    Approach: start with n components and merge

    A depth-first or breadth-first search from every unvisited node also counts components in O(n + e). This lesson uses union-find (disjoint sets) instead, which has a different strength: it can process edges one at a time and still answer "are these two nodes connected?" almost instantly, without searching the graph again.

    The idea is to count backwards. Before any edge is used, every node is alone, so there are n components. Each edge then either joins two different groups, which leaves one component fewer, or connects two nodes that are already in the same group, which changes nothing. The answer is n minus the number of edges that actually merged something.

    Each group is stored as a tree in an array: parent[i] is the node that i points to, and the root, the one node that is its own parent, names the group. Two nodes are in the same group exactly when following parents from each leads to the same root.

    Two tricks keep the trees shallow:

    • Union by size. When merging, the smaller tree goes under the root of the larger one. A node only moves deeper when its group at least doubles in size, so a path to a root never exceeds about log2(n) steps.
    • Path halving. While walking up to a root, each node is pointed at its grandparent, so later walks from there are shorter.

    With both, a lookup or a merge costs O(α(n)) on average, where α is the inverse Ackermann function. It grows so slowly that it stays below 5 for any input a computer can hold, so the total is nearly O(n + e).

    Step by step

    1. Make every node its own parent. Array.from({length: n}, (_, i) => i) calls the arrow function once per index and keeps what it returns, so parent[i] is i. The first parameter is the unused value, hence the underscore.
    2. Create size, an array of n ones. size[r] is the number of nodes in the group whose root is r. Only the roots' entries are kept up to date.
    3. Start components at n, declared with let because it goes down.
    4. Loop over the edges with for...of.
    5. Find the roots of both ends, in rootA and rootB. They are declared with let because the next step may swap them. The find helper is written last.
    6. Compare the roots. If they are equal, the edge closes a cycle inside one group and nothing merges. If they differ, the groups must be merged.
    7. Put the larger group's root in rootA. If size[rootA] < size[rootB], swap the two variables with a destructuring assignment.
    8. Hang the smaller tree under the larger one: parent[rootB] = rootA.
    9. Add the sizes: size[rootA] += size[rootB]. The old size of rootB is never read again, because it is no longer a root.
    10. Decrement components: two groups became one.
    11. Return components after the loop.
    12. Write find(parent, x). It loops while parent[x] !== x, so it stops at the root. Inside, it sets parent[x] to parent[parent[x]] (path halving) and then moves x to parent[x]. It returns x, the root.

    The solution in TypeScript

    class Solution {
        countComponents(n: number, edges: number[][]): number {
            const parent: number[] = Array.from({length: n}, (_, i) => i);
            const size: number[] = 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: number[], x: number): number {
            while (parent[x] !== x) {
                parent[x] = parent[parent[x]];
                x = parent[x];
            }
            return x;
        }
    }
    

    Here is the state after each edge of the example with n = 6:

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

    The edge [2,0] changes nothing: both nodes already lead to root 0. Node 5 is never touched, and it stays a component of its own.

    Some TypeScript details:

    • Types are erased. number[] and the return types exist only for the compiler. The emitted JavaScript has none of them.
    • Destructuring swap. [rootA, rootB] = [rootB, rootA] builds a temporary array of the current values and then assigns them back in the other order. It works because both variables were declared with let.
    • new Array(n).fill(1) creates n empty slots and fills each with 1. Without fill, the slots would hold nothing and size[r] += ... would produce NaN.
    • Arrays are shared. find receives the same array object as countComponents, so the changes it makes to parent are visible to the caller. Reassigning x only changes find's own copy of the number.
    • Method calls need this. Inside a class, find(...) alone refers to nothing. The call is this.find(...).

    Complexity

    Time: nearly O(n + e). Setting up the two arrays costs O(n). Each edge makes two find calls and at most one merge, and with union by size and path halving each costs O(α(n)) on average. The total is O(n + e·α(n)), which the note writes as O((n + e)·α(n)).

    Space: O(n). The parent and size arrays hold n numbers each. find uses a loop, so there is no recursion and no extra stack.

    Edge cases and common mistakes

    • No edges. Every node is its own component, so n = 4 with edges = [] returns 4, and n = 1 returns 1.
    • Cycles. Comparing roots before merging is what keeps the count right. Decrementing for every edge would give 6 - 4 = 2 on the example above instead of 3.
    • Comparing the nodes instead of the roots. edge[0] !== edge[1] is always true here, because an edge never joins a node to itself. The check has to be on the roots.
    • Updating the wrong size. After a swap, rootA is the larger group's root. Adding to the other entry would corrupt the sizes and lose the depth guarantee.
    • A long path. With 100,000 nodes joined in a line, the method still works because find is a loop. A recursive find or a recursive DFS on such a path can run out of call stack.
    • Forgetting this before find in the call.

    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 = 4, edges = [] gives 4.
    • n = 4, edges = [[0, 1], [2, 3], [1, 2]] gives 1.
    • n = 100000 with the edges [i, i + 1] for every i from 0 to 99998 gives 1.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free