Start learning free

LESSON 278 OF 314 · GRAPHS

Connected Components in C#: Union-Find on an Edge List

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

    C# · GRAPHS

    Number Of Connected Components In An Undirected Graph in C#, explained

    Problem overview

    The method CountComponents receives n, the number of nodes (numbered 0 to n - 1), and edges, an int[][] in which every inner array holds the two ends of an undirected edge. 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 is a component by itself.

    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 n = 6 and edges [0,1], [1,2], [2,0], [3,4], nodes 0, 1, 2 form a cycle, 3 and 4 a second group, and node 5 is alone: the answer is 3.

    Approach: start with n groups and merge

    A search (DFS or BFS) from every node not yet visited also counts components in O(n + e), but it needs an adjacency list, and a recursive DFS down a path of 100,000 nodes can run out of call stack. This lesson uses union-find, also called disjoint sets, which works straight from the edge list.

    Before any edge is read, every node is a group of its own, so there are n components. Each edge joins the groups of its two ends. If the ends are in different groups, the groups become one, and the component count drops by exactly 1. If they are already in the same group, the edge changes nothing, which is what happens with the edge [2,0] in the cycle example.

    Each group is stored as a tree where every node points to a parent. The root, the one node that is its own parent, names the group, so two nodes are in the same group exactly when they lead to the same root. Two tricks keep the trees flat:

    • Union by size: when merging, hang the smaller tree under the root of the larger one, so a node only gets deeper when its group at least doubles.
    • Path halving: while walking up to a root, point each node at its grandparent, so later walks are shorter.

    Together they make one Find or merge cost O(α(n)) on average, where α is the inverse Ackermann function, which stays below 5 for any input a computer can hold. In practice that is almost constant.

    Step by step

    1. Create parent and size, two int arrays of length n. parent[x] is the parent of node x; size[r] is the number of nodes in the group whose root is r. Only the roots' sizes are kept current.
    2. Initialise them in one loop. A new int array holds zeros, so the loop sets parent[i] = i (every node is a root) and size[i] = 1.
    3. Set components = n.
    4. Loop over the edges with foreach (int[] edge in edges) and find the roots of edge[0] and edge[1] with the helper Find, written last.
    5. Merge only if the roots differ. Make rootA the root of the larger group by swapping if size[rootA] < size[rootB]. Then point parent[rootB] at rootA, add size[rootB] to size[rootA] and subtract 1 from components. The size of rootB is never read again, because it is no longer a root.
    6. Return components. It started at n and lost 1 for every merge.
    7. Write Find. While parent[x] != x, set parent[x] = parent[parent[x]] (path halving) and move x to parent[x]. When the loop ends, x is the root. A loop needs no call stack, however long the walk.

    Tracing the cycle example (n = 6), printing the arrays after each edge:

    [0,1] merged: parent=[0,0,2,3,4,5] size=[2,1,1,1,1,1] components=5
    [1,2] merged: parent=[0,0,0,3,4,5] size=[3,1,1,1,1,1] components=4
    [2,0] same group: parent=[0,0,0,3,4,5] size=[3,1,1,1,1,1] components=4
    [3,4] merged: parent=[0,0,0,3,3,5] size=[3,1,1,2,1,1] components=3
    

    The edge [2,0] finds the same root, 0, for both ends, so nothing changes. Node 5 never appears in an edge and stays its own root.

    The solution in C#

    class Solution {
        public int CountComponents(int n, int[][] edges) {
            int[] parent = new int[n];
            int[] size = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                size[i] = 1;
            }
            int components = n;
            foreach (int[] edge in edges) {
                int rootA = Find(parent, edge[0]);
                int 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;
        }
    
        public int Find(int[] parent, int x) {
            while (parent[x] != x) {
                parent[x] = parent[parent[x]];
                x = parent[x];
            }
            return x;
        }
    }
    

    The C# details worth knowing:

    • Tuple swap. (rootA, rootB) = (rootB, rootA); builds a pair from the right-hand values and unpacks it into the left-hand variables, so no temporary variable is needed.
    • Arrays are passed by reference. Find receives the same parent array, so its path halving is visible to CountComponents. The parameter x is an int and is copied, so moving it inside Find doesn't affect the caller.
    • int[][] is a jagged array: an array of arrays, so edge is itself an int[] and is read as edge[0]. An empty edge list is an empty array, and foreach simply does nothing.

    Complexity

    Time: O((n + e) · α(n)), nearly O(n + e). Setting up the arrays is O(n), and each of the e edges costs two Find calls and a constant amount of merging.

    Space: O(n) for parent and size.

    Edge cases and common mistakes

    • No edges. The answer is n: with n = 4 and an empty list it returns 4, and with n = 1 it returns 1.
    • A cycle. An edge between nodes already in one group must not lower the count. Comparing the roots before merging is what prevents it.
    • Comparing nodes instead of roots. Checking edge[0] != edge[1] says nothing about whether they are connected.
    • Forgetting size[i] = 1. The sizes would start at 0 and union by size would compare meaningless numbers.
    • Merging a non-root. Set parent on the roots, not on edge[0] or edge[1], or other nodes of those groups are left behind.
    • Large inputs. With n = 100000 and a single path through all the nodes, the method returns 1 without any recursion.

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