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
- Create
parent.Array.from({length: n}, (_, i) => i)builds an array whereparent[i]isi: every node starts as the root of a group of one. The callback gets the value (unused, hence_) and the index. - Create
size, filled with 1. Only the entries of roots are kept current. They decide which tree goes under which. - Start
componentsatnwithlet, because it goes down with every merge. - Loop over
edgeswithfor...of. Each edge either merges two groups or lies inside one. - Find the roots of both endpoints with
this.find, intorootAandrootB. They useletbecause the next step may swap them. The helper is written last. - 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.
- Make
rootAthe larger root. Ifsize[rootA] < size[rootB], swap the two variables with a destructuring assignment. - Hang the smaller tree under the larger:
parent[rootB] = rootA. - Update the size:
size[rootA] += size[rootB]. The value ofsize[rootB]is never read again, becauserootBis no longer a root. - Decrement
components. Two components became one. - Return
componentsafter the loop. - Write
find(parent, x). It is a method of the same class, called throughthis. The array is passed by reference, so changes made insidefindare visible incountComponents. - Loop while
parent[x] !== x. Only a root is its own parent. A loop needs no call stack, however long the walk. - Point
xat its grandparent withparent[x] = parent[parent[x]]. This is path halving. - Move up with
x = parent[x]. That is the old grandparent, so each turn climbs two levels. - 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.fromversusfill.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.fromwith a callback creates a fresh value per index.- Parameters are reassignable. The loop in
findchangesx, the local copy of the argument. The caller's variable is untouched, but theparentarray, 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 = 4andedges = [], the loop never runs and the method returns4. Withn = 1it returns1. - 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
nhandles this automatically. - Cycles. An edge between nodes that already share a root must not decrement
components. Decrementing once per edge would give1instead of3for 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
sizefor 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
findor depth-first search over a long path can overflow the call stack. Thewhileloop infindavoids that.
Testing
These inputs were run against the solution:
n = 5,edges = [[0, 1], [1, 2], [3, 4]]gives2.n = 5,edges = [[0, 1], [1, 2], [2, 3], [3, 4]]gives1.n = 6,edges = [[0, 1], [1, 2], [2, 0], [3, 4]]gives3.n = 4,edges = [[0, 1], [2, 3], [1, 2]]gives1.n = 5,edges = [[0, 1], [2, 3]]gives3.n = 4,edges = []gives4.- A path through 100,000 nodes (
[0, 1],[1, 2], and so on) gives1without a stack overflow.
