Start learning free

LESSON 278 OF 314 · GRAPHS

Connected Components in Kotlin: Union-Find with Path Halving

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

    KOTLIN · GRAPHS

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

    Problem overview

    The function countComponents receives n, the number of nodes (numbered 0 to n - 1), and edges, an Array<IntArray> where each pair [a, b] is an undirected edge. It returns how many connected components the graph has. A component is a group of nodes that can reach each other through edges, with no edge leaving the group. A node with no edges counts as a component of its own.

    Take n = 6 and edges [[0, 1], [1, 2], [2, 0], [3, 4]]. Nodes 0, 1 and 2 form a cycle, nodes 3 and 4 are joined by one edge, and node 5 stands alone. That makes 3 components. The edge [2, 0] changes nothing, because 0 and 2 were already connected through node 1.

    Approach: union-find

    The statement asks for nearly linear time, O((n + e) * α(n)), and O(n) extra space. Union-find (also called disjoint sets) fits that budget.

    The idea is to start pessimistic and count down. With no edges used yet, every node is its own group, so there are n components. Each edge then either joins two different groups, which removes one component, or joins two nodes that are already in the same group, which changes nothing.

    To tell groups apart, each group is stored as a tree. Every node points to a parent, and the root, the one node that is its own parent, names the group. Two nodes are in the same group exactly when walking up from each of them ends at the same root.

    Two tricks keep the trees shallow:

    • Path halving: while walking up to the root, point each node at its grandparent. Later walks from those nodes are shorter.
    • Union by size: when merging, hang the root of the smaller tree under the root of the larger one. A node only gets deeper when its group at least doubles, so no path is longer than log2(n).

    With both tricks a find or a merge costs O(α(n)) on average, where α is the inverse Ackermann function. It stays below 5 for any size a computer can hold, so the cost is practically constant. A depth-first or breadth-first search from each unvisited node also counts components in O(n + e). Union-find is worth knowing because it keeps answering "are these two connected?" cheaply while edges arrive one at a time.

    Step by step

    1. Create parent. IntArray(n) { it } runs the block once per index, so parent[i] starts as i: every node is the root of a group of one.
    2. Create size, an IntArray of ones. size[r] counts the nodes in the group rooted at r. Only the roots' entries stay up to date, and only they are ever read.
    3. Declare components as a var equal to n. It goes down with every successful merge.
    4. Loop over edges.
    5. Find both roots. rootA and rootB are vars because the next step may swap them. The lesson writes find last and uses it first, which keeps the main loop short.
    6. Merge only when the roots differ. Equal roots mean the edge closes a cycle.
    7. Make rootA the larger group's root. If size[rootA] < size[rootB], swap them through a temporary val.
    8. Hang the smaller tree under the larger. Set parent[rootB] to rootA, then add size[rootB] to size[rootA]. The size of rootB is never read again.
    9. Subtract 1 from components and, after the loop, return it.
    10. Write find. Copy node into a var x, since Kotlin parameters can't be reassigned. While parent[x] != x, set parent[x] to parent[parent[x]] (path halving) and move x to parent[x]. When the loop stops, x is the root.

    The solution in Kotlin

    class Solution {
        fun countComponents(n: Int, edges: Array<IntArray>): Int {
            val parent = IntArray(n) { it }
            val size = IntArray(n) { 1 }
            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]) {
                        val temp = rootA
                        rootA = rootB
                        rootB = temp
                    }
                    parent[rootB] = rootA
                    size[rootA] += size[rootB]
                    components--
                }
            }
            return components
        }
    
        fun find(parent: IntArray, node: Int): Int {
            var x = node
            while (parent[x] != x) {
                parent[x] = parent[parent[x]]
                x = parent[x]
            }
            return x
        }
    }
    

    Here is the state after each edge of the example above:

    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 third edge changes neither array, because 2 and 0 already lead to root 0.

    The Kotlin details worth knowing:

    • Arrays are passed by reference. find receives the same parent array, so its path halving is visible to countComponents. The reference parent is a val, but its elements can change.
    • IntArray(n) { it } is the constructor that takes a size and an init block, where it is the index. IntArray(n) alone would fill the array with zeros.
    • var versus val. rootA and rootB are reassigned in the swap, so they must be var. temp never changes, so it is a val.
    • Loops instead of recursion. find uses a while loop. A recursive version would use one stack frame per level, and a chain of 100,000 nodes could overflow the call stack.

    Complexity

    Time: O((n + e) * α(n)). Building the two arrays is O(n). The loop handles each of the e edges with two finds and at most one merge, and each find costs O(α(n)) on average thanks to path halving and union by size.

    Space: O(n). The parent and size arrays hold one integer per node. Nothing else grows with the input.

    Edge cases and common mistakes

    • No edges. The loop doesn't run, so the answer is n. For n = 4 and no edges the function returns 4, and for n = 1 it returns 1.
    • Isolated nodes. A node that appears in no edge is a component. Counting only nodes that appear in edges would miss it.
    • Cycles. An edge between nodes that already share a root must not lower the count. Subtracting once per edge would give a wrong answer for any graph with a cycle.
    • Comparing nodes instead of roots. edge[0] != edge[1] is always true here. The test has to compare the roots.
    • Reading size of a non-root. After a merge only the surviving root's size is meaningful. Compare sizes of roots, not of arbitrary nodes.
    • Forgetting the swap. Without union by size the code still gives the right answer, but the trees can grow into long chains and the running time can degrade.

    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 Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free