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
- Create
parent, anintarray of sizen.parent[x]holds the parent of nodex. - Create
size, another array of sizen.size[r]counts the nodes in the group whose root isr. Only the roots' entries need to be right. - Initialise both in one loop. A new
intarray holds zeros, so setparent[i] = i(every node is its own root) andsize[i] = 1. - Start
componentsatn, since nothing has been merged yet. - Loop over the edges. For each edge find the roots of its two ends with the helper
find, written last, and call themrootAandrootB. - Act only if the roots differ. Equal roots mean the edge closes a cycle or repeats a connection.
- Make
rootAthe larger group's root. Ifsize[rootA] < size[rootB], swap the two with a temporary variable. - Merge. Set
parent[rootB] = rootA, addsize[rootB]tosize[rootA]and subtract one fromcomponents. - Return
components. - Write
find(int[] parent, int x). Whileparent[x] != x, setparent[x] = parent[parent[x]](path halving), thenx = parent[x]. When the loop stops,xis 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.
findreceives the array itself, not a copy, so when it rewritesparent[x]the change is visible tocountComponents. That is what makes path halving pay off across calls. - Parameters are copies. Assigning to
xinsidefindchanges only the method's own copy of the number. The caller's variable is untouched. - A loop instead of recursion. The
whileloop 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 overwriterootAand lose its old value. - The enhanced
for.for (int[] edge : edges)visits each inner array in turn. Eachedgeis the original row, withedge[0]andedge[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
parentandsize. A fresh array is all zeros, which would make every node point at node 0 and every size 0. - Updating
sizeof the wrong root. After the swap,rootAis the surviving root, so the sizes are added intosize[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.
