Problem overview
The method countComponents(n: Int, edges: Array[Array[Int]]): Int receives n nodes, numbered 0 to n - 1, and a list of undirected edges. 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 counts as 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 another, so the answer is 2. With n = 6 and edges [0, 1], [1, 2], [2, 0], [3, 4], the three-node cycle is one component, nodes 3 and 4 a second, and the lonely node 5 a third: the answer is 3.
Approach: start with n groups and merge
A search (BFS or DFS) from every node that hasn't been visited also counts the components in O(n + e). This lesson uses union-find instead, which handles edges one at a time and never needs an adjacency list.
The idea: at the start every node is a group of its own, so there are n components. Each edge either joins two different groups, which removes one component, or connects two nodes that are already in the same group, which changes nothing. So the answer is n minus the number of edges that actually merged two groups.
Each group is stored as a tree in an array parent: parent(i) is the node above i, and the root, the node that is its own parent, names the group. Two nodes are in the same group exactly when walking up from each leads to the same root.
Two tricks keep the trees shallow:
- Union by size: when merging, hang the smaller tree under the root of the larger one. A node only gets deeper when its group at least doubles, so no walk to a root is longer than log2(n) steps.
- Path halving: while walking up, point each node at its grandparent. Later walks over the same nodes are about half as long.
With both, one find or merge costs O(α(n)) on average, where α is the inverse Ackermann function, below 5 for any size a computer can hold. Over all edges that is O((n + e)·α(n)), nearly O(n + e), with O(n) extra space for the two arrays.
Step by step
- Create
parentwithArray.tabulate(n)(i => i): every node starts as its own root. - Create
sizewithArray.fill(n)(1). Only the roots' entries matter:size(r)is the number of nodes in the group whose root isr. - Declare
componentsas avarset ton. It goes down with every merge. - Loop over the edges. For each one, find the roots of its two ends with the helper
find, written last. They arevars because the next step may swap them. - If the roots differ, the edge joins two groups. Swap the roots if needed so that
rootAis the root of the larger group, setparent(rootB) = rootA, addsize(rootB)tosize(rootA)and subtract 1 fromcomponents. If the roots are equal, the edge closes a cycle and nothing happens. - After the loop,
componentsis the last expression, so it is the result. - The helper
findcopiesnodeinto avar x, because Scala parameters can't be reassigned. Whilexisn't its own parent, it setsparent(x)toparent(parent(x))and moves up toparent(x). It ends withx, the root.
The solution in Scala
class Solution {
def countComponents(n: Int, edges: Array[Array[Int]]): Int = {
val parent = Array.tabulate(n)(i => i)
val size = Array.fill(n)(1)
var components = n
for (edge <- 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 -= 1
}
}
components
}
def find(parent: Array[Int], node: Int): Int = {
var x = node
while (parent(x) != x) {
parent(x) = parent(parent(x))
x = parent(x)
}
x
}
}
Scala details
- An
Arrayis passed by reference, so whenfindhalves a path by assigning toparent(x),countComponentssees the change. Avalarray can still have its elements changed:valfixes the name, not the contents. finduses awhileloop, not recursion, so a long chain of nodes can't overflow the call stack.size(rootA) += size(rootB)andcomponents -= 1are compound assignments; Scala has no++or--.- The last expression of a block is its value, so
componentsandxon their own lines act as the returns. - The helper is defined after the method that calls it. Inside a class that is fine.
Tracing the first example
With n = 5 and the edges [0, 1], [1, 2], [3, 4], the arrays after each edge are:
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
On the second edge, the root of node 1 is 0 (size 2) and the root of node 2 is 2 (size 1), so node 2 goes under node 0.
Complexity
Time is O((n + e)·α(n)): building the arrays is O(n), and each of the e edges costs two find calls and at most one merge, each O(α(n)) on average. Space is O(n) for parent and size.
Edge cases and common mistakes
- No edges: every node is alone, so the answer is
n. Forn = 4with no edges the method returns 4, and forn = 1it returns 1. - Cycles and redundant edges: only edges that join different roots lower the count. Subtracting for every edge gives too small an answer.
- Comparing nodes instead of roots: two nodes are connected when
findgives the same root, not whenparentvalues match. - Merging roots versus nodes: set
parent(rootB), notparent(edge(1)); otherwise the rest of the second group stays behind. - Forgetting the size update: without
size, long chains can form. Results stay correct but the cost guarantee is lost. - Large inputs: a path of 100000 nodes (edges
[0, 1],[1, 2], and so on) gives 1 with no stack problems, since nothing here recurses.
