Start learning free

LESSON 278 OF 314 · GRAPHS

Connected Components in Swift: 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 18
    Ctrl + Enter to check

    SWIFT · GRAPHS

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

    Problem overview

    The method countComponents(_ n: Int, _ edges: [[Int]]) -> Int receives the number of nodes, n, numbered 0 to n - 1, and a list of undirected edges. It returns how many connected components the graph has. A component is a group of nodes that can reach each other through edges, and a node with no edges counts as a component of its own.

    For n = 5 and edges = [[0, 1], [1, 2], [3, 4]] the answer is 2: nodes 0, 1 and 2 form one group, nodes 3 and 4 the other. For n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]] the answer is 3. Nodes 0, 1 and 2 form a cycle, 3 and 4 a second group, and node 5 stands alone.

    The lesson asks for roughly O(n + e) time, where e is the number of edges, and O(n) extra space.

    Approach: start with n groups and merge

    A depth-first or breadth-first search from every unvisited node also counts components in O(n + e). This lesson uses union-find (disjoint sets) instead, which fits the problem in a different way. Begin by treating every node as a group of its own, so there are n components. Each edge then either joins two different groups, which leaves one component fewer, or joins two nodes that are already connected, which changes nothing.

    Each group is stored as a tree in which every node points to a parent. The root, the one node that is its own parent, names the group. Two nodes are in the same group exactly when following parents from each leads to the same root.

    Two tricks keep the trees shallow:

    • Union by size. When merging, the root of the smaller tree is hung under the root of the larger one.
    • Path halving. While walking up to a root, each node is pointed at its grandparent, so later walks from there are shorter.

    With both, a lookup or a merge costs O(α(n)) on average, where α is the inverse Ackermann function. It stays below 5 for any n a computer can hold, so the whole algorithm is nearly linear.

    The lookup is a loop rather than a recursive function. With up to 100,000 nodes, a recursive search up a long chain could run out of call stack.

    Step by step

    1. Create parent as Array(0..<n), so parent[i] is i: every node is its own root. It is a var because lookups will change it.
    2. Create size with [Int](repeating: 1, count: n). Only the roots' entries stay accurate. They decide which tree goes under which.
    3. Start components at n. It goes down with every successful merge.
    4. Loop over edges. Each edge is an array of two node numbers.
    5. Find both roots with find(&parent, edge[0]) and find(&parent, edge[1]). They are vars because the next step may swap them. The & passes parent to an inout parameter.
    6. Merge only if the roots differ. Equal roots mean the edge closes a cycle.
    7. Make rootA the larger group by swapping the two roots with a tuple assignment when size[rootA] < size[rootB].
    8. Hang the smaller tree under the larger one with parent[rootB] = rootA.
    9. Add the sizes: size[rootA] += size[rootB]. The entry for rootB is never read again.
    10. Subtract one from components: two groups became one.
    11. Return components after the loop.
    12. Write find. It copies node into a var x, loops while parent[x] != x, points parent[x] to its grandparent, moves x to parent[x], and returns x once it is a root.

    The solution in Swift

    class Solution {
        func countComponents(_ n: Int, _ edges: [[Int]]) -> Int {
            var parent = Array(0..<n)
            var size = [Int](repeating: 1, count: n)
            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] {
                        (rootA, rootB) = (rootB, rootA)
                    }
                    parent[rootB] = rootA
                    size[rootA] += size[rootB]
                    components -= 1
                }
            }
            return components
        }
        func find(_ parent: inout [Int], _ node: Int) -> Int {
            var x = node
            while parent[x] != x {
                parent[x] = parent[parent[x]]
                x = parent[x]
            }
            return x
        }
    }
    

    The Swift details worth a closer look:

    • inout and &. Arrays are value types, so a plain parameter would receive a copy and the changes would be lost. An inout parameter writes its final value back to the caller's variable, and the call site marks it with &. The caller's variable must be a var.
    • Parameters are constants. find can't change node, which is why it copies it into var x first.
    • The swap. (rootA, rootB) = (rootB, rootA) builds a pair from the right side and then assigns both variables, so no temporary variable is needed.
    • No -- operator. Swift has none, so the counter goes down with components -= 1.
    • Array(0..<n). The half-open range 0..<n holds 0 to n - 1; wrapping it in Array(...) gives [0, 1, ..., n - 1].

    Watching the components shrink

    For n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]], here is parent and components after each edge:

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

    The edge [2, 0] changes nothing: nodes 2 and 0 already lead to the same root, 0.

    Complexity

    Time: O((n + e)·α(n)). Building the arrays is O(n). Each of the e edges costs two lookups and at most one merge, each O(α(n)) on average because of union by size and path halving.

    Space: O(n). parent and size each hold n integers. find uses a loop, so it adds no call stack.

    Edge cases and common mistakes

    • No edges. The loop never runs and the answer is n: countComponents(4, []) returns 4.
    • A single node. countComponents(1, []) returns 1.
    • Cycles. An edge between nodes that already share a root must not decrease the count. The rootA != rootB check handles it.
    • Forgetting inout. Without it Swift won't let find assign to parent, and a copy would not keep the shortened paths anyway.
    • Comparing nodes instead of roots. Testing edge[0] != edge[1] is always true here. The roots are what identify groups.
    • Merging roots the wrong way. Set parent[rootB], not parent[edge[1]]. Attaching a non-root node would split its old group.
    • A long chain. A path of 100,000 nodes, 0 - 1 - 2 - ... - 99999, returns 1. The loop in find never recurses, so its depth doesn't matter.

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