Problem overview
The method countComponents(_ n: Int, _ edges: [[Int]]) -> Int receives the number of nodes, n, numbered 0 to n - 1, and a list of undirected edges. It returns how many connected components the graph has. A component is a group of nodes that can reach each other through edges, and a node with no edges counts as a component of its own.
For n = 5 and edges = [[0, 1], [1, 2], [3, 4]] the answer is 2: nodes 0, 1 and 2 form one group, nodes 3 and 4 the other. For n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]] the answer is 3. Nodes 0, 1 and 2 form a cycle, 3 and 4 a second group, and node 5 stands 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 depth-first or breadth-first search from every unvisited node also counts components in O(n + e). This lesson uses union-find (disjoint sets) instead, which fits the problem in a different way. Begin by treating every node as a group of its own, so there are n components. Each edge then either joins two different groups, which leaves one component fewer, or joins two nodes that are already connected, which changes nothing.
Each group is stored as a tree in which every node points to a parent. The root, the one node that is its own parent, names the group. Two nodes are in the same group exactly when following parents from each leads to the same root.
Two tricks keep the trees shallow:
- Union by size. When merging, the root of the smaller tree is hung under the root of the larger one.
- Path halving. While walking up to a root, each node is pointed at its grandparent, so later walks from there are shorter.
With both, a lookup or a merge costs O(α(n)) on average, where α is the inverse Ackermann function. It stays below 5 for any n a computer can hold, so the whole algorithm is nearly linear.
The lookup is a loop rather than a recursive function. With up to 100,000 nodes, a recursive search up a long chain could run out of call stack.
Step by step
- Create
parentasArray(0..<n), soparent[i]isi: every node is its own root. It is avarbecause lookups will change it. - Create
sizewith[Int](repeating: 1, count: n). Only the roots' entries stay accurate. They decide which tree goes under which. - Start
componentsatn. It goes down with every successful merge. - Loop over
edges. Each edge is an array of two node numbers. - Find both roots with
find(&parent, edge[0])andfind(&parent, edge[1]). They arevars because the next step may swap them. The&passesparentto aninoutparameter. - Merge only if the roots differ. Equal roots mean the edge closes a cycle.
- Make
rootAthe larger group by swapping the two roots with a tuple assignment whensize[rootA] < size[rootB]. - Hang the smaller tree under the larger one with
parent[rootB] = rootA. - Add the sizes:
size[rootA] += size[rootB]. The entry forrootBis never read again. - Subtract one from
components: two groups became one. - Return
componentsafter the loop. - Write
find. It copiesnodeinto avar x, loops whileparent[x] != x, pointsparent[x]to its grandparent, movesxtoparent[x], and returnsxonce it is a root.
The solution in Swift
class Solution {
func countComponents(_ n: Int, _ edges: [[Int]]) -> Int {
var parent = Array(0..<n)
var size = [Int](repeating: 1, count: n)
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] {
(rootA, rootB) = (rootB, rootA)
}
parent[rootB] = rootA
size[rootA] += size[rootB]
components -= 1
}
}
return components
}
func find(_ parent: inout [Int], _ node: Int) -> Int {
var x = node
while parent[x] != x {
parent[x] = parent[parent[x]]
x = parent[x]
}
return x
}
}
The Swift details worth a closer look:
inoutand&. Arrays are value types, so a plain parameter would receive a copy and the changes would be lost. Aninoutparameter writes its final value back to the caller's variable, and the call site marks it with&. The caller's variable must be avar.- Parameters are constants.
findcan't changenode, which is why it copies it intovar xfirst. - The swap.
(rootA, rootB) = (rootB, rootA)builds a pair from the right side and then assigns both variables, so no temporary variable is needed. - No
--operator. Swift has none, so the counter goes down withcomponents -= 1. Array(0..<n). The half-open range0..<nholds0ton - 1; wrapping it inArray(...)gives[0, 1, ..., n - 1].
Watching the components shrink
For n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]], here is parent and components after each edge:
start parent=[0, 1, 2, 3, 4, 5] components=6
[0, 1] parent=[0, 0, 2, 3, 4, 5] components=5
[1, 2] parent=[0, 0, 0, 3, 4, 5] components=4
[2, 0] parent=[0, 0, 0, 3, 4, 5] components=4
[3, 4] parent=[0, 0, 0, 3, 3, 5] components=3
The edge [2, 0] changes nothing: nodes 2 and 0 already lead to the same root, 0.
Complexity
Time: O((n + e)·α(n)). Building the arrays is O(n). Each of the e edges costs two lookups and at most one merge, each O(α(n)) on average because of union by size and path halving.
Space: O(n). parent and size each hold n integers. find uses a loop, so it adds no call stack.
Edge cases and common mistakes
- No edges. The loop never runs and the answer is
n:countComponents(4, [])returns 4. - A single node.
countComponents(1, [])returns 1. - Cycles. An edge between nodes that already share a root must not decrease the count. The
rootA != rootBcheck handles it. - Forgetting
inout. Without it Swift won't letfindassign toparent, and a copy would not keep the shortened paths anyway. - Comparing nodes instead of roots. Testing
edge[0] != edge[1]is always true here. The roots are what identify groups. - Merging roots the wrong way. Set
parent[rootB], notparent[edge[1]]. Attaching a non-root node would split its old group. - A long chain. A path of 100,000 nodes,
0 - 1 - 2 - ... - 99999, returns 1. The loop infindnever recurses, so its depth doesn't matter.
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 = 4,edges = []gives4.n = 1,edges = []gives1.
