Problem overview
The method countComponents receives n, the number of nodes (numbered 0 to n - 1), and a vector<vector<int>> named edges. Each edge [a, b] joins two nodes in both directions. It returns how many connected components the graph has: groups of nodes that can reach one another, with no edge leaving the group. A node with no edges counts as a component of its own.
For n = 5 and edges = [[0, 1], [1, 2], [3, 4]], nodes 0, 1 and 2 form one group and nodes 3 and 4 another, so the answer is 2. For n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]] the answer is 3: the cycle 0-1-2, the pair 3-4, and the lonely node 5. The edge 2-0 joins nodes that were already connected through node 1, so it changes nothing.
The statement asks for nearly linear time, O((n + e)·α(n)) with e edges, and O(n) extra space.
Approach: union-find
A search (DFS or BFS) from every unvisited node also counts components in O(n + e). This lesson uses union-find instead, which handles edges one at a time and always knows which nodes are connected.
The idea is to start with n components, one per node, and let every edge try to merge two of them. Each group is stored as a tree where every node points to a parent. The root, the one node that is its own parent, names the group. Two nodes are in the same group exactly when they lead to the same root.
For each edge, find the two roots. If they differ, the edge joins two groups: merge them and subtract one from the count. If they are equal, the edge closes a cycle and the count stays.
Two tricks keep the trees shallow, so that finding a root costs O(α(n)) on average, where α is the inverse Ackermann function and stays below 5 for any realistic n:
- Union by size: hang the root of the smaller tree under the root of the larger one.
- Path halving: while walking up to the root, point each node at its grandparent.
Here is the first example traced with the lesson's code, printing parent and size after each edge:
edge 0-1 parent=0 0 2 3 4 size=2 1 1 1 1 components=4
edge 1-2 parent=0 0 0 3 4 size=3 1 1 1 1 components=3
edge 3-4 parent=0 0 0 3 3 size=3 1 1 2 1 components=2
Only the sizes of roots matter: node 1's entry stays 1 after it stops being a root.
Step by step
- Create
parentwith one slot per node. - Create
size, filled with 1: every node starts as a group of one. Only roots keep a meaningful size. - Loop over the nodes and set
parent[i] = i, making each node the root of its own group. - Start
componentsatn, since no edge has been used yet. - Loop over the edges by reference with
auto&, so no edge is copied. - Find both roots with the
findhelper, written last. - If the roots differ, make
rootAthe root of the larger group by swapping whensize[rootA] < size[rootB]. - Attach
rootBunderrootAand add its size torootA's. - Decrease
components: two groups became one. - Return
components. - Write
find: it takesparentby reference, because it changes it, and loops whileparent[x] != x. In the loop it pointsxat its grandparent, then movesxto that node. It returns the root.
The solution in C++
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
vector<int> parent(n);
vector<int> size(n, 1);
for (int i = 0; i < n; i++) {
parent[i] = i;
}
int components = n;
for (auto& edge : edges) {
int rootA = find(parent, edge[0]);
int rootB = find(parent, edge[1]);
if (rootA != rootB) {
if (size[rootA] < size[rootB]) {
swap(rootA, rootB);
}
parent[rootB] = rootA;
size[rootA] += size[rootB];
components--;
}
}
return components;
}
int find(vector<int>& parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
};
C++ details worth knowing:
- Constructors.
vector<int> parent(n)makesnzeros, andvector<int> size(n, 1)makesnones. Parentheses give a size here; braces would make a list of values. - Reference parameter.
vector<int>& parentletsfindchange the caller's vector. Without the&, each call would copy allnelements and the shortening would be lost. xis a copy. Theint xparameter is passed by value, so moving it up the tree doesn't change the caller's variable.- Order of members.
countComponentscallsfindbefore it appears in the class. That is fine: inside a class, member function bodies can use members declared later. - Loop, not recursion.
finduses awhileloop. A recursive version on a long chain could use a lot of call stack. Withn = 100000and the edges[i, i + 1]forming one path, the lesson's code returns 1. swapexchanges the two local ints, which only reorders which root is calledrootA.
Complexity
Time: O((n + e)·α(n)). Setting up is O(n). Each of the e edges makes two find calls, and with union by size and path halving each call costs O(α(n)) on average. Union by size alone already keeps every path within log2(n) steps.
Space: O(n). The vectors parent and size hold one int per node.
Edge cases and common mistakes
- No edges. With
n = 4and no edges the loop never runs and the answer is 4. - Edges inside a group. A cycle edge has equal roots and must not decrease
components. Subtracting once per edge gives wrong answers. - Comparing the nodes instead of the roots. Nodes
0and2in[[0, 1], [1, 2]]are connected although no edge joins them directly. Only roots tell. - Forgetting the
&infind's signature. The code still compiles, but it copies the vector on every call, which is far too slow for 100,000 nodes. - Merging the wrong things. Set
parent[rootB], notparent[edge[1]]. Attaching a non-root node would cut it off from its own group.
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 = 1, no edges gives 1, andn = 4, no edges gives 4.n = 4,edges = [[0, 1], [2, 3], [1, 2]]gives 1: the last edge merges two groups of two.
