Problem overview
The method CountComponents receives n, the number of nodes (numbered 0 to n - 1), and edges, an int[][] in which every inner array holds the two ends of an undirected edge. It returns how many connected components the graph has: groups of nodes that can reach each other, with no edge leaving the group. A node with no edges is a component by itself.
With n = 5 and edges [0,1], [1,2], [3,4], the nodes 0, 1, 2 form one group and 3, 4 another, so the answer is 2. With n = 6 and edges [0,1], [1,2], [2,0], [3,4], nodes 0, 1, 2 form a cycle, 3 and 4 a second group, and node 5 is alone: the answer is 3.
Approach: start with n groups and merge
A search (DFS or BFS) from every node not yet visited also counts components in O(n + e), but it needs an adjacency list, and a recursive DFS down a path of 100,000 nodes can run out of call stack. This lesson uses union-find, also called disjoint sets, which works straight from the edge list.
Before any edge is read, every node is a group of its own, so there are n components. Each edge joins the groups of its two ends. If the ends are in different groups, the groups become one, and the component count drops by exactly 1. If they are already in the same group, the edge changes nothing, which is what happens with the edge [2,0] in the cycle example.
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, so two nodes are in the same group exactly when they lead to the same root. Two tricks keep the trees flat:
- Union by size: when merging, hang the smaller tree under the root of the larger one, so a node only gets deeper when its group at least doubles.
- Path halving: while walking up to a root, point each node at its grandparent, so later walks are shorter.
Together they make one Find or merge cost O(α(n)) on average, where α is the inverse Ackermann function, which stays below 5 for any input a computer can hold. In practice that is almost constant.
Step by step
- Create
parentandsize, twointarrays of lengthn.parent[x]is the parent of nodex;size[r]is the number of nodes in the group whose root isr. Only the roots' sizes are kept current. - Initialise them in one loop. A new
intarray holds zeros, so the loop setsparent[i] = i(every node is a root) andsize[i] = 1. - Set
components = n. - Loop over the edges with
foreach (int[] edge in edges)and find the roots ofedge[0]andedge[1]with the helperFind, written last. - Merge only if the roots differ. Make
rootAthe root of the larger group by swapping ifsize[rootA] < size[rootB]. Then pointparent[rootB]atrootA, addsize[rootB]tosize[rootA]and subtract 1 fromcomponents. The size ofrootBis never read again, because it is no longer a root. - Return
components. It started atnand lost 1 for every merge. - Write
Find. Whileparent[x] != x, setparent[x] = parent[parent[x]](path halving) and movextoparent[x]. When the loop ends,xis the root. A loop needs no call stack, however long the walk.
Tracing the cycle example (n = 6), printing the arrays after each edge:
[0,1] merged: parent=[0,0,2,3,4,5] size=[2,1,1,1,1,1] components=5
[1,2] merged: parent=[0,0,0,3,4,5] size=[3,1,1,1,1,1] components=4
[2,0] same group: parent=[0,0,0,3,4,5] size=[3,1,1,1,1,1] components=4
[3,4] merged: parent=[0,0,0,3,3,5] size=[3,1,1,2,1,1] components=3
The edge [2,0] finds the same root, 0, for both ends, so nothing changes. Node 5 never appears in an edge and stays its own root.
The solution in C#
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;
foreach (int[] edge in edges) {
int rootA = Find(parent, edge[0]);
int rootB = 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;
}
public int Find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
}
The C# details worth knowing:
- Tuple swap.
(rootA, rootB) = (rootB, rootA);builds a pair from the right-hand values and unpacks it into the left-hand variables, so no temporary variable is needed. - Arrays are passed by reference.
Findreceives the sameparentarray, so its path halving is visible toCountComponents. The parameterxis anintand is copied, so moving it insideFinddoesn't affect the caller. int[][]is a jagged array: an array of arrays, soedgeis itself anint[]and is read asedge[0]. An empty edge list is an empty array, andforeachsimply does nothing.
Complexity
Time: O((n + e) · α(n)), nearly O(n + e). Setting up the arrays is O(n), and each of the e edges costs two Find calls and a constant amount of merging.
Space: O(n) for parent and size.
Edge cases and common mistakes
- No edges. The answer is
n: withn = 4and an empty list it returns 4, and withn = 1it returns 1. - A cycle. An edge between nodes already in one group must not lower the count. Comparing the roots before merging is what prevents it.
- Comparing nodes instead of roots. Checking
edge[0] != edge[1]says nothing about whether they are connected. - Forgetting
size[i] = 1. The sizes would start at 0 and union by size would compare meaningless numbers. - Merging a non-root. Set
parenton the roots, not onedge[0]oredge[1], or other nodes of those groups are left behind. - Large inputs. With
n = 100000and a single path through all the nodes, the method returns 1 without any recursion.
Testing
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 = 4with no edges gives4.n = 100000with the path[i, i+1]for everyigives1.
