Problem overview
The function count_components receives n, the number of nodes (numbered 0 to n - 1), and edges, a vector of pairs where each pair is an undirected edge. It returns how many connected components the graph has. A component is a group of nodes that can all reach each other, and a node with no edges is a component of its own.
With 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. With the path [[0, 1], [1, 2], [2, 3], [3, 4]] the answer is 1. With 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 the lone node 5.
Approach: union-find
Start by assuming every node is its own component, so there are n of them. Each edge then either joins two different groups, which removes one component, or connects two nodes that are already in the same group, which changes nothing. The answer is n minus the number of edges that merged two groups.
To tell which case an edge falls in, union-find (also called disjoint sets) stores each group as a tree. Every node holds a parent, and the root, which is its own parent, names the group. Two nodes are in the same group exactly when they lead up to the same root.
Two tricks keep the trees shallow. Union by size hangs the smaller tree under the root of the larger one, so a node only gets deeper when its group at least doubles. Path halving makes each node visited on the way to the root point to its grandparent, which flattens the tree for later searches. With both, one search or merge costs O(α(n)) on average, where α is the inverse Ackermann function, which stays below 5 for any n a computer can hold. The total is O((n + e)·α(n)), nearly linear.
A depth-first or breadth-first search from every unvisited node also counts components in O(n + e). For a graph with 100,000 nodes in a line, a recursive depth-first search can exhaust the call stack, so it needs an explicit stack. Union-find is worth knowing because it can answer "are these two connected?" after each new edge without searching the graph again.
Here is the third example edge by edge. Each row is the state after that edge:
start: parent=[0, 1, 2, 3, 4, 5] size=[1, 1, 1, 1, 1, 1] components=6
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 edge [2, 0] changes nothing: nodes 2 and 0 already have the root 0.
Step by step
- Create
parent. It is aVec<usize>holding 0, 1, …, n - 1, built by collecting the range0..n as usize. Each node starts as its own root. - Create
size, a vector ofnones. Only the entries of roots are kept up to date, and they decide which tree goes under which. - Create
componentsas a mutablei32equal ton. - Loop over
&edges. The&borrows the vector instead of moving it. - Find both roots with
Self::find:root_aforedge[0]androot_bforedge[1]. They aremutbecause the next step may swap them. The edge values arei32, so each needsas usizeto be an index. - Merge only if the roots differ. Equal roots mean the edge closes a cycle.
- Make
root_athe root of the larger group, swapping the two roots withstd::mem::swapwhensize[root_a] < size[root_b]. - Attach the smaller tree: set
parent[root_b]toroot_a. - Add the sizes:
size[root_a] += size[root_b]. The size ofroot_bis never read again. - Subtract 1 from
components. Rust has no--operator. - Return
componentsafter the loop, without a semicolon. - Write
find, an associated function that takesparent: &mut Vec<usize>andmut x: usizeand returns the root ofx. Themut xlets it movexup the tree. - Loop while
parent[x] != x, that is, whilexisn't a root. - Halve the path: set
parent[x]toparent[parent[x]], the grandparent. - Move up: set
xtoparent[x], which is now the old grandparent. - Return
x, the root.
The solution in Rust
impl Solution {
fn count_components(n: i32, edges: Vec<Vec<i32>>) -> i32 {
let mut parent: Vec<usize> = (0..n as usize).collect();
let mut size = vec![1; n as usize];
let mut components = n;
for edge in &edges {
let mut root_a = Self::find(&mut parent, edge[0] as usize);
let mut root_b = Self::find(&mut parent, edge[1] as usize);
if root_a != root_b {
if size[root_a] < size[root_b] {
std::mem::swap(&mut root_a, &mut root_b);
}
parent[root_b] = root_a;
size[root_a] += size[root_b];
components -= 1;
}
}
components
}
fn find(parent: &mut Vec<usize>, mut x: usize) -> usize {
while parent[x] != x {
parent[x] = parent[parent[x]];
x = parent[x];
}
x
}
}
Rust details worth knowing:
- Two integer types. The input uses
i32, but vector indexes must beusize, so every node read fromedgesis cast withas usize. The resultcomponentsstays ani32, because the function returns one. - Borrowing.
find(&mut parent, ...)lends the vector mutably for the duration of the call, since path halving writes into it. The call ends before the next line runs, soparentis free again for the assignmentparent[root_b] = root_a. std::mem::swap. It exchanges the values behind two mutable references, so&mut root_a, &mut root_bswaps the two local variables.- The type of
size.vec![1; n as usize]doesn't name an element type, and nothing else in the function fixes it, so Rust uses the default integer type,i32. Group sizes never exceed 100,000, so that is plenty. Self::find.findhas noselfparameter, so it is called through the type, asSelf::find, even from another method of the sameimpl.- No recursion.
findis a loop, so a long chain of parents can't overflow the call stack.
Complexity
Time: O((n + e)·α(n)). Building the two vectors is O(n). Each of the e edges does two finds and at most one merge, each costing O(α(n)) on average. For practical sizes this is the same as O(n + e).
Space: O(n). The parent and size vectors have one entry per node.
Edge cases and common mistakes
- No edges. The answer is
n: withn = 4and no edges the function returns 4, and withn = 1it returns 1. - Cycles. An edge between two nodes that already share a root must not decrease
components. The checkroot_a != root_bhandles it. - Comparing nodes instead of roots. Checking
edge[0] != edge[1]says nothing about connection. Always compare roots. - Merging nodes instead of roots. Setting
parent[edge[1]]directly would detach a node from its group. The merge must hang one root under the other. - Long chains. A path of 100,000 nodes,
0 - 1 - 2 - ..., returns 1, and becausefindis iterative there is no stack-depth risk. - Isolated nodes. Nodes that appear in no edge still count, which is why
componentsstarts atn.
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.
