Start learning free

LESSON 278 OF 314 · GRAPHS

Connected Components in Go: 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

    GO · GRAPHS

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

    Problem overview

    The function countComponents receives n, the number of nodes (numbered 0 to n - 1), and edges, a slice of pairs. Each pair [a, b] is an undirected edge: you can walk from a to b and back. It returns the number of connected components, meaning groups of nodes that can all reach each other with no edge leaving the group. A node with no edges is 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 form another, so the answer is 2. With n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]] the answer is 3: the triangle 0, 1, 2, the pair 3, 4 and the lone node 5. The edge [2, 0] joins two nodes that are already connected through node 1, so it changes nothing.

    Approach: start with n groups and merge them

    Begin by pretending there are no edges: every node is its own component, so there are n of them. Then take the edges one by one. If an edge joins two nodes that are in different groups, the two groups become one, and the count drops by 1. If both nodes are already in the same group, the edge closes a cycle and the count stays the same. After the last edge, what is left is the answer.

    That needs a fast way to ask "which group is this node in?" and to merge two groups. This is the job of union-find (also called disjoint sets). Each group is a tree stored in a slice called parent: parent[x] is the node above x, 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 those trees shallow:

    • Union by size. A second slice, size, records how many nodes each root's tree holds. When merging, the smaller tree is hung under the root of the larger one, so a node only gets deeper when its group at least doubles in size.
    • Path halving. While walking up to the root, each node is pointed at its grandparent, so later walks are shorter.

    With both, one find or merge costs O(α(n)) on average, where α is the inverse Ackermann function, which stays below 5 for any size a computer can hold. The total is close to O(n + e) for e edges.

    A depth-first or breadth-first search from every unvisited node also counts components in O(n + e). Union-find has an extra strength: it can answer "are these two connected?" after each new edge without searching the graph again.

    Step by step

    1. Create parent and size with make, each a slice of n ints. Both start filled with zeros.
    2. Initialise them in a loop. Set parent[i] = i so every node is the root of its own group, and size[i] = 1 because each group holds one node.
    3. Set components to n.
    4. Loop over edges with range, dropping the index with _.
    5. Find both roots with the helper find, written at the end, and store them in rootA and rootB.
    6. Merge only if the roots differ. Equal roots mean the nodes are already together.
    7. Make rootA the larger root. If size[rootA] is smaller, swap the two variables.
    8. Hang the smaller tree under the larger by setting parent[rootB] to rootA, and add size[rootB] to size[rootA]. The size of rootB is never read again, because it is no longer a root.
    9. Subtract 1 from components: two groups became one.
    10. Return components after the loop.
    11. Write find. While parent[x] != x, point parent[x] at parent[parent[x]], then move x to its new parent. When the loop stops, x is the root.

    The solution in Go

    func countComponents(n int, edges [][]int) int {
        parent := make([]int, n)
        size := make([]int, n)
        for i := 0; i < n; i++ {
            parent[i] = i
            size[i] = 1
        }
        components := n
        for _, edge := range edges {
            rootA := find(parent, edge[0])
            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--
            }
        }
        return components
    }
    func find(parent []int, x int) int {
        for parent[x] != x {
            parent[x] = parent[parent[x]]
            x = parent[x]
        }
        return x
    }
    

    The Go details worth a closer look:

    • Slices are shared. find receives the slice header by value, but it points at the same underlying array, so the assignments to parent[x] inside find are visible in countComponents. Assigning to x, on the other hand, changes only find's own copy of the number.
    • Swapping in one line. rootA, rootB = rootB, rootA evaluates the whole right side before assigning, so no temporary variable is needed.
    • A loop instead of recursion. Go has no while; for parent[x] != x is a for with only a condition. Walking up needs no recursion, however tall a tree is.
    • A nil slice of edges is fine. Ranging over nil runs zero times, so countComponents(4, nil) returns 4.

    Watching the state change

    Here is the state after each edge for n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]], printed from a run of the solution:

    start [0 1 2 3 4 5] [1 1 1 1 1 1] 6
    [0 1] parent [0 0 2 3 4 5] size [2 1 1 1 1 1] components 5
    [1 2] parent [0 0 0 3 4 5] size [3 1 1 1 1 1] components 4
    [2 0] parent [0 0 0 3 4 5] size [3 1 1 1 1 1] components 4
    [3 4] parent [0 0 0 3 3 5] size [3 1 1 2 1 1] components 3
    

    The edge [1, 2] hangs node 2, the smaller tree, under root 0. The edge [2, 0] finds root 0 for both nodes and leaves everything unchanged.

    Complexity

    Time: O((n + e) · α(n)), nearly O(n + e). Initialising the slices is O(n). Each of the e edges costs two find calls and a constant amount of merging work, and union by size with path halving makes each find cost O(α(n)) on average.

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

    Edge cases and common mistakes

    • No edges. Every node is alone, so the answer is n. An empty slice and nil both work.
    • Isolated nodes. A node that appears in no edge still counts. Starting components at n handles it; counting only nodes that appear in edges would miss it.
    • Cycles. An edge between nodes that already share a root must not decrement the count. Decrementing for every edge would give a wrong answer for the triangle example.
    • Merging the nodes instead of the roots. Setting parent[edge[0]] directly would cut that node away from its own group. Always merge the roots that find returns.
    • Forgetting to set size to 1. make fills it with zeros, so every comparison between sizes would tie and the sizes would stay wrong.
    • Edge order. [3, 2], [1, 0], [2, 1] with n = 4 gives 1, the same as any other ordering of the same graph.
    • Long chains. A path of 100,000 nodes, with edges [0, 1], [1, 2], …, returns 1. The loop-based find and the size rule keep that fast.

    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.
    • n = 4, edges = [[3, 2], [1, 0], [2, 1]] gives 1.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free