Problem overview
The function countComponents receives n, the number of nodes (numbered 0 to n - 1), and edges, an Array<IntArray> where each pair [a, b] is an undirected edge. It returns how many connected components the graph has. A component is a group of nodes that can reach each other through edges, with no edge leaving the group. A node with no edges counts as a component of its own.
Take n = 6 and edges [[0, 1], [1, 2], [2, 0], [3, 4]]. Nodes 0, 1 and 2 form a cycle, nodes 3 and 4 are joined by one edge, and node 5 stands alone. That makes 3 components. The edge [2, 0] changes nothing, because 0 and 2 were already connected through node 1.
Approach: union-find
The statement asks for nearly linear time, O((n + e) * α(n)), and O(n) extra space. Union-find (also called disjoint sets) fits that budget.
The idea is to start pessimistic and count down. With no edges used yet, every node is its own group, so there are n components. Each edge then either joins two different groups, which removes one component, or joins two nodes that are already in the same group, which changes nothing.
To tell groups apart, each group is stored as a tree. Every node points to a parent, 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 the trees shallow:
- Path halving: while walking up to the root, point each node at its grandparent. Later walks from those nodes are shorter.
- Union by size: when merging, hang the root of the smaller tree 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).
With both tricks a find or a merge costs O(α(n)) on average, where α is the inverse Ackermann function. It stays below 5 for any size a computer can hold, so the cost is practically constant. A depth-first or breadth-first search from each unvisited node also counts components in O(n + e). Union-find is worth knowing because it keeps answering "are these two connected?" cheaply while edges arrive one at a time.
Step by step
- Create
parent.IntArray(n) { it }runs the block once per index, soparent[i]starts asi: every node is the root of a group of one. - Create
size, anIntArrayof ones.size[r]counts the nodes in the group rooted atr. Only the roots' entries stay up to date, and only they are ever read. - Declare
componentsas avarequal ton. It goes down with every successful merge. - Loop over
edges. - Find both roots.
rootAandrootBarevars because the next step may swap them. The lesson writesfindlast and uses it first, which keeps the main loop short. - Merge only when the roots differ. Equal roots mean the edge closes a cycle.
- Make
rootAthe larger group's root. Ifsize[rootA] < size[rootB], swap them through a temporaryval. - Hang the smaller tree under the larger. Set
parent[rootB]torootA, then addsize[rootB]tosize[rootA]. The size ofrootBis never read again. - Subtract 1 from
componentsand, after the loop, return it. - Write
find. Copynodeinto avar x, since Kotlin parameters can't be reassigned. Whileparent[x] != x, setparent[x]toparent[parent[x]](path halving) and movextoparent[x]. When the loop stops,xis the root.
The solution in Kotlin
class Solution {
fun countComponents(n: Int, edges: Array<IntArray>): Int {
val parent = IntArray(n) { it }
val size = IntArray(n) { 1 }
var components = n
for (edge in edges) {
var rootA = find(parent, edge[0])
var rootB = find(parent, edge[1])
if (rootA != rootB) {
if (size[rootA] < size[rootB]) {
val temp = rootA
rootA = rootB
rootB = temp
}
parent[rootB] = rootA
size[rootA] += size[rootB]
components--
}
}
return components
}
fun find(parent: IntArray, node: Int): Int {
var x = node
while (parent[x] != x) {
parent[x] = parent[parent[x]]
x = parent[x]
}
return x
}
}
Here is the state after each edge of the example above:
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 changes neither array, because 2 and 0 already lead to root 0.
The Kotlin details worth knowing:
- Arrays are passed by reference.
findreceives the sameparentarray, so its path halving is visible tocountComponents. The referenceparentis aval, but its elements can change. IntArray(n) { it }is the constructor that takes a size and an init block, whereitis the index.IntArray(n)alone would fill the array with zeros.varversusval.rootAandrootBare reassigned in the swap, so they must bevar.tempnever changes, so it is aval.- Loops instead of recursion.
finduses awhileloop. A recursive version would use one stack frame per level, and a chain of 100,000 nodes could overflow the call stack.
Complexity
Time: O((n + e) * α(n)). Building the two arrays is O(n). The loop handles each of the e edges with two finds and at most one merge, and each find costs O(α(n)) on average thanks to path halving and union by size.
Space: O(n). The parent and size arrays hold one integer per node. Nothing else grows with the input.
Edge cases and common mistakes
- No edges. The loop doesn't run, so the answer is
n. Forn = 4and no edges the function returns 4, and forn = 1it returns 1. - Isolated nodes. A node that appears in no edge is a component. Counting only nodes that appear in edges would miss it.
- Cycles. An edge between nodes that already share a root must not lower the count. Subtracting once per edge would give a wrong answer for any graph with a cycle.
- Comparing nodes instead of roots.
edge[0] != edge[1]is always true here. The test has to compare the roots. - Reading
sizeof a non-root. After a merge only the surviving root's size is meaningful. Compare sizes of roots, not of arbitrary nodes. - Forgetting the swap. Without union by size the code still gives the right answer, but the trees can grow into long chains and the running time can degrade.
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.
