Problem overview
The function countComponents receives n, the number of nodes (numbered 0 to n - 1), and edges, a slice of pairs. Each pair [a, b] is an undirected edge: you can walk from a to b and back. It returns the number of connected components, meaning groups of nodes that can all 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]], nodes 0, 1 and 2 form one group and nodes 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 triangle 0, 1, 2, the pair 3, 4 and the lone node 5. The edge [2, 0] joins two nodes that are already connected through node 1, so it changes nothing.
Approach: start with n groups and merge them
Begin by pretending there are no edges: every node is its own component, so there are n of them. Then take the edges one by one. If an edge joins two nodes that are in different groups, the two groups become one, and the count drops by 1. If both nodes are already in the same group, the edge closes a cycle and the count stays the same. After the last edge, what is left is the answer.
That needs a fast way to ask "which group is this node in?" and to merge two groups. This is the job of union-find (also called disjoint sets). Each group is a tree stored in a slice called parent: parent[x] is the node above x, 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 of them ends at the same root.
Two tricks keep those trees shallow:
- Union by size. A second slice,
size, records how many nodes each root's tree holds. When merging, the smaller tree is hung under the root of the larger one, so a node only gets deeper when its group at least doubles in size. - Path halving. While walking up to the root, each node is pointed at its grandparent, so later walks are shorter.
With both, one find or merge costs O(α(n)) on average, where α is the inverse Ackermann function, which stays below 5 for any size a computer can hold. The total is close to O(n + e) for e edges.
A depth-first or breadth-first search from every unvisited node also counts components in O(n + e). Union-find has an extra strength: it can answer "are these two connected?" after each new edge without searching the graph again.
Step by step
- Create
parentandsizewithmake, each a slice ofnints. Both start filled with zeros. - Initialise them in a loop. Set
parent[i] = iso every node is the root of its own group, andsize[i] = 1because each group holds one node. - Set
componentston. - Loop over
edgeswithrange, dropping the index with_. - Find both roots with the helper
find, written at the end, and store them inrootAandrootB. - Merge only if the roots differ. Equal roots mean the nodes are already together.
- Make
rootAthe larger root. Ifsize[rootA]is smaller, swap the two variables. - Hang the smaller tree under the larger by setting
parent[rootB]torootA, and addsize[rootB]tosize[rootA]. The size ofrootBis never read again, because it is no longer a root. - Subtract 1 from
components: two groups became one. - Return
componentsafter the loop. - Write
find. Whileparent[x] != x, pointparent[x]atparent[parent[x]], then movexto its new parent. When the loop stops,xis the root.
The solution in Go
func countComponents(n int, edges [][]int) int {
parent := make([]int, n)
size := make([]int, n)
for i := 0; i < n; i++ {
parent[i] = i
size[i] = 1
}
components := n
for _, edge := range edges {
rootA := find(parent, edge[0])
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
}
func find(parent []int, x int) int {
for parent[x] != x {
parent[x] = parent[parent[x]]
x = parent[x]
}
return x
}
The Go details worth a closer look:
- Slices are shared.
findreceives the slice header by value, but it points at the same underlying array, so the assignments toparent[x]insidefindare visible incountComponents. Assigning tox, on the other hand, changes onlyfind's own copy of the number. - Swapping in one line.
rootA, rootB = rootB, rootAevaluates the whole right side before assigning, so no temporary variable is needed. - A loop instead of recursion. Go has no
while;for parent[x] != xis aforwith only a condition. Walking up needs no recursion, however tall a tree is. - A nil slice of edges is fine. Ranging over
nilruns zero times, socountComponents(4, nil)returns 4.
Watching the state change
Here is the state after each edge for n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]], printed from a run of the solution:
start [0 1 2 3 4 5] [1 1 1 1 1 1] 6
[0 1] parent [0 0 2 3 4 5] size [2 1 1 1 1 1] components 5
[1 2] parent [0 0 0 3 4 5] size [3 1 1 1 1 1] components 4
[2 0] parent [0 0 0 3 4 5] size [3 1 1 1 1 1] components 4
[3 4] parent [0 0 0 3 3 5] size [3 1 1 2 1 1] components 3
The edge [1, 2] hangs node 2, the smaller tree, under root 0. The edge [2, 0] finds root 0 for both nodes and leaves everything unchanged.
Complexity
Time: O((n + e) · α(n)), nearly O(n + e). Initialising the slices is O(n). Each of the e edges costs two find calls and a constant amount of merging work, and union by size with path halving makes each find cost O(α(n)) on average.
Space: O(n). The parent and size slices hold one int per node. Nothing else grows with the input.
Edge cases and common mistakes
- No edges. Every node is alone, so the answer is
n. An empty slice andnilboth work. - Isolated nodes. A node that appears in no edge still counts. Starting
componentsatnhandles it; counting only nodes that appear in edges would miss it. - Cycles. An edge between nodes that already share a root must not decrement the count. Decrementing for every edge would give a wrong answer for the triangle example.
- Merging the nodes instead of the roots. Setting
parent[edge[0]]directly would cut that node away from its own group. Always merge the roots thatfindreturns. - Forgetting to set
sizeto 1.makefills it with zeros, so every comparison between sizes would tie and the sizes would stay wrong. - Edge order.
[3, 2], [1, 0], [2, 1]withn = 4gives 1, the same as any other ordering of the same graph. - Long chains. A path of 100,000 nodes, with edges
[0, 1], [1, 2], …, returns 1. The loop-basedfindand the size rule keep that fast.
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 = 1,edges = []gives1.n = 4,edges = []gives4.n = 4,edges = [[3, 2], [1, 0], [2, 1]]gives1.
