Start learning free

LESSON 278 OF 314 · GRAPHS

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

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 20
    Ctrl + Enter to check

    SCALA · GRAPHS

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

    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

    1. Create parent with Array.tabulate(n)(i => i): every node starts as its own root.
    2. Create size with Array.fill(n)(1). Only the roots' entries matter: size(r) is the number of nodes in the group whose root is r.
    3. Declare components as a var set to n. It goes down with every merge.
    4. Loop over the edges. For each one, find the roots of its two ends with the helper find, written last. They are vars because the next step may swap them.
    5. If the roots differ, the edge joins two groups. Swap the roots if needed so that rootA is the root of the larger group, set parent(rootB) = rootA, add size(rootB) to size(rootA) and subtract 1 from components. If the roots are equal, the edge closes a cycle and nothing happens.
    6. After the loop, components is the last expression, so it is the result.
    7. The helper find copies node into a var x, because Scala parameters can't be reassigned. While x isn't its own parent, it sets parent(x) to parent(parent(x)) and moves up to parent(x). It ends with x, 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 Array is passed by reference, so when find halves a path by assigning to parent(x), countComponents sees the change. A val array can still have its elements changed: val fixes the name, not the contents.
    • find uses a while loop, not recursion, so a long chain of nodes can't overflow the call stack.
    • size(rootA) += size(rootB) and components -= 1 are compound assignments; Scala has no ++ or --.
    • The last expression of a block is its value, so components and x on 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. For n = 4 with no edges the method returns 4, and for n = 1 it 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 find gives the same root, not when parent values match.
    • Merging roots versus nodes: set parent(rootB), not parent(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.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free