Problem overview
The method countComponents receives n, the number of nodes (numbered 0 to n - 1), and a list edges of pairs. Each pair [a, b] is an undirected edge. A connected component is a group of nodes that can reach each other by following 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.
For 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. 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 node 5 alone.
The lesson asks for roughly O(n + e) time, where e is the number of edges, and O(n) extra space.
Approach: start with n groups and merge
A DFS or BFS from every unvisited node also counts components in O(n + e). This lesson uses union-find (disjoint sets) instead, which counts by merging rather than exploring.
The idea is simple. Before any edge is read, every node is a group of its own, so there are n components. Each edge either joins two different groups, which leaves one component fewer, or joins two nodes that are already in the same group, which changes nothing. After all the edges, the counter holds the answer.
To tell whether two nodes share a group, each group is stored as a tree. Every node has a parent, and the root of a tree is the one node that is its own parent. The root names the group: two nodes are in the same group exactly when walking up from each of them ends at the same root.
Two tricks keep the trees shallow so that walking up stays cheap:
- Union by size: when merging, the root of the smaller tree goes under the root of the larger one.
- Path halving: while walking up, each node is pointed at its grandparent, so later walks from it are shorter.
With both, one find or one merge costs O(α(n)) on average, where α is the inverse Ackermann function. It grows so slowly that it stays below 5 for any n a computer can hold, so the whole algorithm behaves like O(n + e).
Step by step
- Every node is its own parent.
parent = list(range(n))gives[0, 1, 2, ..., n - 1], so every node is the root of a group of one. - Track group sizes.
size = [1] * n. Only the entries of roots are kept up to date, and they decide which tree goes under which. - Start the count at n.
components = n, one per node. - Loop over the edges. Each one is looked at once.
- Find both roots.
rootAandrootBcome from a helper,find, which the lesson writes last. Writing the main loop first keeps it short. - Merge only when the roots differ. Equal roots mean the edge closes a cycle inside one group.
- Put the larger group on top. If
size[rootA] < size[rootB], swap the two names, sorootAalways names the larger tree. - Hang the smaller tree under it, with
parent[rootB] = rootA. - Update the size of the new root, with
size[rootA] += size[rootB].rootBisn't a root any more, so its size is never read again. - One component fewer.
components -= 1. - Return
componentsafter the loop. - Write
find. Whileparent[x] != x, setparent[x] = parent[parent[x]](path halving) and move up withx = parent[x]. When the loop stops,xis the root.
The solution in Python
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
parent = list(range(n))
size = [1] * n
components = n
for edge in edges:
rootA = self.find(parent, edge[0])
rootB = self.find(parent, edge[1])
if rootA != rootB:
if size[rootA] < size[rootB]:
rootA, rootB = rootB, rootA
parent[rootB] = rootA
size[rootA] += size[rootB]
components -= 1
return components
def find(self, parent: List[int], x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
Python details worth knowing
- Tuple assignment swaps without a temporary. In
rootA, rootB = rootB, rootA, Python builds the right-hand side first and then assigns, so the two names trade values. - Lists are passed by reference.
findreceives the same list object ascountComponents, so when it rewritesparent[x]for path halving, the caller sees the change. That is intended: it is how the trees get flatter over time. finduses a loop, not recursion. A recursive version would climb one call per level, and Python's default recursion limit is about 1,000 calls. Union by size keeps trees shallow, but a loop never has the problem.list(range(n))builds[0, 1, ..., n - 1]in one expression.
Trace on the first example
Running the solution on n = 5 with edges = [[0, 1], [1, 2], [3, 4]] gives these states after each edge:
| Edge | parent | size | components |
|---|---|---|---|
[0, 1] | [0, 0, 2, 3, 4] | [2, 1, 1, 1, 1] | 4 |
[1, 2] | [0, 0, 0, 3, 4] | [3, 1, 1, 1, 1] | 3 |
[3, 4] | [0, 0, 0, 3, 3] | [3, 1, 1, 2, 1] | 2 |
On the first edge the sizes tie, so no swap happens and node 1 goes under node 0. On the second edge, node 1's root is 0 (size 2) and node 2's root is 2 (size 1), so node 2 goes under 0. The cycle example n = 6 with [[0, 1], [1, 2], [2, 0], [3, 4]] shows the other case: the third edge, [2, 0], finds both nodes under root 0 and leaves components at 4, so the final result is 3.
Complexity
Time: building parent and size costs O(n). Each edge makes two find calls and at most one merge, and each of those costs O(α(n)) on average, so the loop costs O(e · α(n)). In total that is O((n + e) · α(n)), which is nearly O(n + e).
Space: parent and size each hold n numbers, so the extra space is O(n).
Union-find also fits when edges arrive one at a time: after each new edge, it can still tell almost instantly whether two nodes are connected, with no new search of the graph.
Edge cases and common mistakes
- No edges. The loop never runs, and the answer is
n. Forn = 4andedges = []the method returns4; forn = 1it returns1. - Edges inside a group. An edge that closes a cycle must not lower the count. The
rootA != rootBcheck is what protects it. - Comparing parents instead of roots. Two nodes in the same group can have different parents. Only the roots tell you whether they are in the same group, so always call
findfirst. - Updating the size of the wrong node. Add to
size[rootA], the root that survives, and read sizes only at roots. - Isolated nodes. Nodes that appear in no edge, such as node 5 in the cycle example, still count. Starting
componentsatn, not at 0, takes care of them.
Testing
Try these in the editor above. The results come from running the solution:
| n | edges | Result |
|---|---|---|
| 5 | [[0, 1], [1, 2], [3, 4]] | 2 |
| 6 | [[0, 1], [1, 2], [2, 0], [3, 4]] | 3 |
| 4 | [] | 4 |
| 1 | [] | 1 |
