Start learning free

LESSON 278 OF 319 · GRAPHS

Connected Components in Java: 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 22
    Ctrl + Enter to check

    JAVA · GRAPHS

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

    Problem overview

    The method countComponents(int n, int[][] edges) receives the number of nodes, n, and an array of undirected edges. It returns how many connected components the graph has. A component is a group of nodes that can all reach each other, with no edge leaving the group, and a node with no edges counts as a component of its own.

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

    The target is about O(n + e) time for e edges and O(n) extra space. Both n and the number of edges can reach 100,000.

    Approach: start with n groups and merge

    A search (DFS or BFS) from every node not yet visited also counts the components in O(n + e). On a graph this large, a recursive DFS down a path of 100,000 nodes can overflow the call stack, so it needs an explicit stack or a queue. This lesson uses a different tool, union-find (also called disjoint sets).

    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 removes one component, or connects two nodes that are already in the same group, which removes nothing. The answer is n minus the number of edges that actually merged two groups.

    To tell which case an edge is, each group is stored as a tree. Every node has a parent, and the root, the one node that is its own parent, names the group. Two nodes are in the same group exactly when walking up from each leads to the same root.

    Two tricks keep those trees shallow, which keeps the walks short:

    • 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 about log2(n).
    • Path halving. While walking up, each node is pointed at its grandparent, so later walks from that node skip a level.

    With both tricks a find or a merge costs O(α(n)) on average, where α, the inverse Ackermann function, stays below 5 for any input a computer can hold. Overall that is nearly O(n + e). A useful bonus: union-find still works when edges arrive one at a time, because it can answer "are these two connected?" after every new edge without searching the graph again.

    Step by step

    1. Create parent, an int array of size n. parent[x] holds the parent of node x.
    2. Create size, another array of size n. size[r] counts the nodes in the group whose root is r. Only the roots' entries need to be right.
    3. Initialise both in one loop. A new int array holds zeros, so set parent[i] = i (every node is its own root) and size[i] = 1.
    4. Start components at n, since nothing has been merged yet.
    5. Loop over the edges. For each edge find the roots of its two ends with the helper find, written last, and call them rootA and rootB.
    6. Act only if the roots differ. Equal roots mean the edge closes a cycle or repeats a connection.
    7. Make rootA the larger group's root. If size[rootA] < size[rootB], swap the two with a temporary variable.
    8. Merge. Set parent[rootB] = rootA, add size[rootB] to size[rootA] and subtract one from components.
    9. Return components.
    10. Write find(int[] parent, int x). While parent[x] != x, set parent[x] = parent[parent[x]] (path halving), then x = parent[x]. When the loop stops, x is the root.

    The solution in Java

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

    The Java details worth a closer look:

    • Arrays are passed by reference. find receives the array itself, not a copy, so when it rewrites parent[x] the change is visible to countComponents. That is what makes path halving pay off across calls.
    • Parameters are copies. Assigning to x inside find changes only the method's own copy of the number. The caller's variable is untouched.
    • A loop instead of recursion. The while loop needs no call stack, however long the walk is, so deep trees can't cause a stack overflow.
    • The swap needs temp. Without it, the first assignment would overwrite rootA and lose its old value.
    • The enhanced for. for (int[] edge : edges) visits each inner array in turn. Each edge is the original row, with edge[0] and edge[1] as its two nodes.

    Complexity

    Time: nearly O(n + e). Initialising the arrays is O(n). Each of the e edges does two finds and at most one merge, and with union by size and path halving each find costs O(α(n)) on average. The total is O((n + e)·α(n)).

    Space: O(n). The parent and size arrays hold one number per node. Nothing else grows with the input.

    Edge cases and common mistakes

    • No edges. Every node is its own component, so the answer is n. countComponents(4, new int[][]{}) returns 4.
    • Isolated nodes. A node that appears in no edge is never touched, so it stays one component. In the six-node example, node 5 is the third component.
    • Cycles. An edge between two nodes that already share a root must not lower components. Subtracting once per edge instead of once per merge would give a wrong count whenever the graph has a cycle.
    • Comparing nodes instead of roots. Checking edge[0] != edge[1] says nothing about whether the two are connected. Always compare roots.
    • Forgetting to initialise parent and size. A fresh array is all zeros, which would make every node point at node 0 and every size 0.
    • Updating size of the wrong root. After the swap, rootA is the surviving root, so the sizes are added into size[rootA].
    • Recursive search on a long path. A recursive DFS over 100,000 nodes in a line can run out of stack, which is one reason to prefer this loop-based approach.

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