Number of Connected Components in an Undirected Graph

Count the separate groups of linked nodes in a graph by merging groups edge by edge with union-find.

A graph has n nodes, numbered 0 to n - 1, and a list edges. Each edge [a, b] joins node a and node b and can be followed both ways, so the graph is undirected. Return the number of connected components: groups of nodes in which every node can reach every other one by following edges, while no edge leads out of the group.

Example 1
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
Explanation: {0, 1, 2} and {3, 4}.
Example 2
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
Solution

The Idea

Picture five towns, numbered 0 to 4, and a few two-way roads between them. A road from 0 to 1 and another from 1 to 2 let you drive between any two of the towns 0, 1 and 2. A road from 3 to 4 joins those two. No road leads from the first three towns to the last two, so the map falls apart into two separate road networks.

That is Example 1. Each town is a node, each road an edge, and each separate network a connected component. Look at the left half of the picture below: the dashed boxes mark component {0, 1, 2} and component {3, 4}.

Example 1: nodes 0, 1 and 2 joined by edges form one component, and nodes 3 and 4 form another. In the parent links, nodes 1 and 2 point to the root 0 and node 4 points to the root 3, so the parent array is [0, 0, 0, 3, 3].

How could a program count those boxes? It can read the edges one at a time. Before any edge, every node is a group on its own, so there are five groups. Edge 0-1 joins two of them, leaving four. Edge 1-2 joins {0, 1} with {2}, leaving three, and edge 3-4 leaves two, the answer.

Not every edge joins two groups, though. If Example 1 also had an edge 2-0, both its ends would already be in {0, 1, 2}, and the count must not drop. So each edge raises one question: are its two ends already in the same group?

To answer that quickly, let each group pick one of its nodes to stand for it, called the group's root. Every node keeps a link to a parent node in its own group, and a root is its own parent. Following parent links from any node ends at its group's root, so two nodes share a group exactly when they reach the same root.

Now look at the right half of the picture. After the three edges, nodes 1 and 2 point to the root 0, and node 4 points to the root 3. The row labelled parent holds the same links in an array: entry i is the parent of node i, and nodes 0 and 3 are their own parents.

Keeping groups this way, with one operation that follows the links to a node's root and another that joins two groups, is called union-find. Following the links is the find, and joining two groups is the union.

Solution Approach

Turning that idea into code means settling four things: how the count changes, how to tell whether two nodes share a group, which root goes under which, and how to keep the parent links short. Along the way, a plain group label per node shows why parent links are worth it.

Counting the groups

What does the count start at? With no edges every node is alone, so it starts at n. Each edge either joins two different groups, which lowers the count by one, or finds both its ends in one group already, which changes nothing.

Subtracting one for every edge, n minus the number of edges, ignores that second case. Three nodes joined in a triangle by three edges give 3 - 3 = 0, while the true answer is 1.

Telling whether two nodes share a group

How do we know which group a node is in? The plainest way is a label per node: node i stores the number of its group. Checking an edge is then quick, because it compares two labels. Joining two groups is slow, though, since every node with the old label needs the new one, and that can mean going over all n nodes for each edge.

With parent links, joining needs one change: the root of one group gets the other root as its parent. The method find(x) follows parents from x until it reaches a node that is its own parent, and returns that root.

Choosing which root goes under which

Does it matter which root becomes the parent? It does, because careless choices build long chains. Suppose the first end's root always went under the second end's root. The edges of Example 2 would then put 0 under 1, 1 under 2, 2 under 3 and 3 under 4, and a find from node 0 would walk four links.

To avoid that, each root keeps a number called its rank, an upper limit on how tall its group is: the number of parent links from the deepest node up to the root. The root with the smaller rank goes under the other, so the taller group does not grow. When the ranks are equal, either goes under the other and the new root's rank grows by one. This rule is called union by rank.

Keeping the parent links short

Can find leave the links shorter than it found them? On its way to the root it visits every node in between. On the way back it can point each of them straight at the root, so the next find from any of them takes one step. Shortening the links during a find like this is called path compression.

With both rules, a find costs at most about α(n) steps on average over many calls. Here α is the inverse Ackermann function, which grows so slowly that it stays at 4 or less for any n that fits in a computer's memory.

Java Solution

The method countComponents works in these steps:

  1. First, create two arrays of size n: parent, filled with parent[i] = i so every node starts as its own root, and rank, which starts at 0 for every node.
  2. Set the count, components, to n.
  3. Loop over the edges. For each edge e, call union(e[0], e[1]), and if it returns true, two groups became one, so lower components by one.
  4. Inside union, find the root ra of the first end and the root rb of the second. If they are the same, return false. Otherwise put the root with the smaller rank under the other one. On a tie, put rb under ra and add one to rank[ra]. Then return true.
  5. find(x) returns x when it is its own parent. Otherwise it calls itself on parent[x], stores the root it gets back in parent[x], which is the path compression, and returns it.
  6. When the loop over the edges is done, return components.

The main method runs both examples, printing the parent array after Example 1, then a graph with no edges, the triangle with n minus the number of edges beside it, and one edge given three times.

Java
import java.util.Arrays;

public class NumberOfConnectedComponents {
    private int[] parent;
    private int[] rank;

    public int countComponents(int n, int[][] edges) {
        parent = new int[n];
        rank = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;                         // every node starts as its own root
        }
        int components = n;
        for (int[] e : edges) {
            if (union(e[0], e[1])) {
                components--;                      // two groups became one
            }
        }
        return components;
    }

    private int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);           // path compression
        }
        return parent[x];
    }

    // Returns false if a and b were already in the same group.
    private boolean union(int a, int b) {
        int ra = find(a);
        int rb = find(b);
        if (ra == rb) {
            return false;
        }
        if (rank[ra] < rank[rb]) {                 // shorter tree goes under the taller one
            parent[ra] = rb;
        } else if (rank[ra] > rank[rb]) {
            parent[rb] = ra;
        } else {
            parent[rb] = ra;
            rank[ra]++;
        }
        return true;
    }

    public static void main(String[] args) {
        NumberOfConnectedComponents uf = new NumberOfConnectedComponents();
        int[][] ex1 = {{0, 1}, {1, 2}, {3, 4}};
        System.out.println("Example 1: " + uf.countComponents(5, ex1)
                + ", parent = " + Arrays.toString(uf.parent));
        int[][] ex2 = {{0, 1}, {1, 2}, {2, 3}, {3, 4}};
        System.out.println("Example 2: " + uf.countComponents(5, ex2));
        System.out.println("No edges, n = 4: " + uf.countComponents(4, new int[0][]));
        int[][] triangle = {{0, 1}, {1, 2}, {2, 0}};
        System.out.println("Triangle, n = 3: " + uf.countComponents(3, triangle)
                + " (n - edges = " + (3 - triangle.length) + ")");
        int[][] repeated = {{0, 1}, {1, 0}, {0, 1}};
        System.out.println("Edge 0-1 three times, n = 3: " + uf.countComponents(3, repeated));
    }
}

Running it prints:

Output
Example 1: 2, parent = [0, 0, 0, 3, 3]
Example 2: 1
No edges, n = 4: 4
Triangle, n = 3: 1 (n - edges = 0)
Edge 0-1 three times, n = 3: 2

Example 1 counts 2, and its parent array, [0, 0, 0, 3, 3], matches the row in the picture: nodes 1 and 2 point to 0, and node 4 points to 3. Example 2 joins all five nodes into one group, and with no edges at all the four nodes stay four groups.

Look at the triangle line. Union-find counts 1, while n minus the number of edges gives 0. The third edge, 2-0, found both its ends under the root 0, so union returned false and the count stayed. The last line works the same way: only the first copy of edge 0-1 joins two groups, and node 2 stays alone, which makes 2.

Complexity

The work is filling the two arrays, plus one union, with its two finds, for each edge.

  • Time: O(n + E × α(n)), where E is the number of edges, because setting up parent takes n steps and each edge's two finds cost about α(n) steps on average with union by rank and path compression.
  • Space: O(n), because parent and rank hold one entry per node, and union by rank keeps every node at most log2 n parent links from its root, which also limits how deep the recursive find goes.

The same count, with the graph given as a grid of 0s and 1s that says which nodes are linked, is Number of Provinces.