Start learning free

LESSON 278 OF 314 · GRAPHS

Connected Components in Rust: O((n + e)·α(n)) with Union-Find

Practice O((n + e)·α(n)) Read the full explanation

You get an undirected graph with n nodes, labeled 0 to n - 1. Its edges come as an array edges. Each edges[i] = [ai, bi] joins nodes ai and bi.

Return how many connected components the graph has.

A connected component is a group of nodes linked by edges. From any node in the group, you can reach every other one. No edge links two different groups. A node with no edges is a component by itself.

 

Example 1:

Input: n = 6, edges = [[0, 3], [3, 5], [1, 4]]
Output: 3
Explanation: Nodes 0, 3 and 5 are linked.
Nodes 1 and 4 are linked.
Node 2 has no edges at all.
    0 - 3 - 5      1 - 4      2

Example 2:

Input: n = 4, edges = [[2, 0], [0, 1], [1, 2], [1, 3]]
Output: 1
Explanation: All four nodes are linked.
The edge 1 - 2 adds nothing new.
Nodes 1 and 2 are already linked through 0.
    2 - 0
     \ /
      1 - 3

Example 3:

Input: n = 3, edges = []
Output: 3
Explanation: With no edges, each node is a component on its own.

 

Constraints:

  • 1 to 100,000 nodes.
  • 0 to 100,000 edges.
  • Each edge joins two different nodes.
  • Every node in edges is from 0 to n - 1.
  • No edge is listed twice.

Note:

Your algorithm should run in O((n + e)·α(n)) time, nearly O(n + e), where e is the number of edges, and use O(n) extra space.

The tutorial uses union-find, also called disjoint sets. Every node starts as a group of its own, so there are n components. Each edge merges the groups of its two nodes, unless they are already in the same group, and every merge leaves one component fewer. A group is kept as a tree in which each node points to its parent, and the tree's root names the group: two nodes are in the same group exactly when they lead to the same root. Two tricks keep the trees flat: path halving (on the way up to the root, point each node to its grandparent) and union by size (hang the root of the smaller tree under the root of the larger one). With both, finding a root or merging two groups costs O(α(n)) on average, where α is the inverse Ackermann function, which grows so slowly that it stays below 5 for any n a computer can hold.

A DFS or BFS from every node that isn't visited yet, as in Number of Islands, also counts the components in O(n + e); on a graph this big, use a BFS or a DFS with its own stack, since a recursive DFS down a path of 105 nodes can run out of call stack. Union-find is worth knowing because it keeps working while the edges arrive one at a time: after each new edge it can still tell, almost at once, whether two nodes are connected, without searching the graph again.

STEP 1 OF 17
    Ctrl + Enter to check

    RUST · GRAPHS

    Number Of Connected Components In An Undirected Graph in Rust, explained

    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

    1. Create parent. It is a Vec<usize> holding 0, 1, …, n - 1, built by collecting the range 0..n as usize. Each node starts as its own root.
    2. Create size, a vector of n ones. Only the entries of roots are kept up to date, and they decide which tree goes under which.
    3. Create components as a mutable i32 equal to n.
    4. Loop over &edges. The & borrows the vector instead of moving it.
    5. Find both roots with Self::find: root_a for edge[0] and root_b for edge[1]. They are mut because the next step may swap them. The edge values are i32, so each needs as usize to be an index.
    6. Merge only if the roots differ. Equal roots mean the edge closes a cycle.
    7. Make root_a the root of the larger group, swapping the two roots with std::mem::swap when size[root_a] < size[root_b].
    8. Attach the smaller tree: set parent[root_b] to root_a.
    9. Add the sizes: size[root_a] += size[root_b]. The size of root_b is never read again.
    10. Subtract 1 from components. Rust has no -- operator.
    11. Return components after the loop, without a semicolon.
    12. Write find, an associated function that takes parent: &mut Vec<usize> and mut x: usize and returns the root of x. The mut x lets it move x up the tree.
    13. Loop while parent[x] != x, that is, while x isn't a root.
    14. Halve the path: set parent[x] to parent[parent[x]], the grandparent.
    15. Move up: set x to parent[x], which is now the old grandparent.
    16. 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 be usize, so every node read from edges is cast with as usize. The result components stays an i32, 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, so parent is free again for the assignment parent[root_b] = root_a.
    • std::mem::swap. It exchanges the values behind two mutable references, so &mut root_a, &mut root_b swaps 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. find has no self parameter, so it is called through the type, as Self::find, even from another method of the same impl.
    • No recursion. find is 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: with n = 4 and no edges the function returns 4, and with n = 1 it returns 1.
    • Cycles. An edge between two nodes that already share a root must not decrease components. The check root_a != root_b handles 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 because find is iterative there is no stack-depth risk.
    • Isolated nodes. Nodes that appear in no edge still count, which is why components starts at n.

    Testing

    • n = 5, edges = [[0, 1], [1, 2], [3, 4]] gives 2.
    • n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4]] gives 1.
    • n = 6, edges = [[0, 1], [1, 2], [2, 0], [3, 4]] gives 3.
    • n = 1, edges = [] gives 1.
    • n = 4, edges = [] gives 4.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free