Start learning free

LESSON 563 OF 673 · GRAPHS

Connected Components in Python: Union-Find in Near-Linear Time

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 a list 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 17
    Ctrl + Enter to check

    PYTHON · GRAPHS

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

    Problem overview

    The method countComponents receives n, the number of nodes (numbered 0 to n - 1), and a list edges of pairs. Each pair [a, b] is an undirected edge. A connected component is a group of nodes that can reach each other by following edges, with no edge leaving the group. The method returns how many such groups the graph has. A node with no edges counts as a component of its own.

    For 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. For n = 6 and edges = [[0, 1], [1, 2], [2, 0], [3, 4]] the answer is 3: the cycle 0, 1, 2, the pair 3, 4, and node 5 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 DFS or BFS from every unvisited node also counts components in O(n + e). This lesson uses union-find (disjoint sets) instead, which counts by merging rather than exploring.

    The idea is simple. Before any edge is read, every node is a group of its own, so there are n components. Each edge either joins two different groups, which leaves one component fewer, or joins two nodes that are already in the same group, which changes nothing. After all the edges, the counter holds the answer.

    To tell whether two nodes share a group, each group is stored as a tree. Every node has a parent, and the root of a tree is the one node that is its own parent. The root 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 so that walking up stays cheap:

    • Union by size: when merging, the root of the smaller tree goes under the root of the larger one.
    • Path halving: while walking up, each node is pointed at its grandparent, so later walks from it are shorter.

    With both, one find or one merge costs O(α(n)) on average, where α is the inverse Ackermann function. It grows so slowly that it stays below 5 for any n a computer can hold, so the whole algorithm behaves like O(n + e).

    Step by step

    1. Every node is its own parent. parent = list(range(n)) gives [0, 1, 2, ..., n - 1], so every node is the root of a group of one.
    2. Track group sizes. size = [1] * n. Only the entries of roots are kept up to date, and they decide which tree goes under which.
    3. Start the count at n. components = n, one per node.
    4. Loop over the edges. Each one is looked at once.
    5. Find both roots. rootA and rootB come from a helper, find, which the lesson writes last. Writing the main loop first keeps it short.
    6. Merge only when the roots differ. Equal roots mean the edge closes a cycle inside one group.
    7. Put the larger group on top. If size[rootA] < size[rootB], swap the two names, so rootA always names the larger tree.
    8. Hang the smaller tree under it, with parent[rootB] = rootA.
    9. Update the size of the new root, with size[rootA] += size[rootB]. rootB isn't a root any more, so its size is never read again.
    10. One component fewer. components -= 1.
    11. Return components after the loop.
    12. Write find. While parent[x] != x, set parent[x] = parent[parent[x]] (path halving) and move up with x = parent[x]. When the loop stops, x is the root.

    The solution in Python

    class Solution:
        def countComponents(self, n: int, edges: List[List[int]]) -> int:
            parent = list(range(n))
            size = [1] * n
            components = n
            for edge in edges:
                rootA = self.find(parent, edge[0])
                rootB = self.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
    
        def find(self, parent: List[int], x: int) -> int:
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x
    

    Python details worth knowing

    • Tuple assignment swaps without a temporary. In rootA, rootB = rootB, rootA, Python builds the right-hand side first and then assigns, so the two names trade values.
    • Lists are passed by reference. find receives the same list object as countComponents, so when it rewrites parent[x] for path halving, the caller sees the change. That is intended: it is how the trees get flatter over time.
    • find uses a loop, not recursion. A recursive version would climb one call per level, and Python's default recursion limit is about 1,000 calls. Union by size keeps trees shallow, but a loop never has the problem.
    • list(range(n)) builds [0, 1, ..., n - 1] in one expression.

    Trace on the first example

    Running the solution on n = 5 with edges = [[0, 1], [1, 2], [3, 4]] gives these states after each edge:

    Edgeparentsizecomponents
    [0, 1][0, 0, 2, 3, 4][2, 1, 1, 1, 1]4
    [1, 2][0, 0, 0, 3, 4][3, 1, 1, 1, 1]3
    [3, 4][0, 0, 0, 3, 3][3, 1, 1, 2, 1]2

    On the first edge the sizes tie, so no swap happens and node 1 goes under node 0. On the second edge, node 1's root is 0 (size 2) and node 2's root is 2 (size 1), so node 2 goes under 0. The cycle example n = 6 with [[0, 1], [1, 2], [2, 0], [3, 4]] shows the other case: the third edge, [2, 0], finds both nodes under root 0 and leaves components at 4, so the final result is 3.

    Complexity

    Time: building parent and size costs O(n). Each edge makes two find calls and at most one merge, and each of those costs O(α(n)) on average, so the loop costs O(e · α(n)). In total that is O((n + e) · α(n)), which is nearly O(n + e).

    Space: parent and size each hold n numbers, so the extra space is O(n).

    Union-find also fits when edges arrive one at a time: after each new edge, it can still tell almost instantly whether two nodes are connected, with no new search of the graph.

    Edge cases and common mistakes

    • No edges. The loop never runs, and the answer is n. For n = 4 and edges = [] the method returns 4; for n = 1 it returns 1.
    • Edges inside a group. An edge that closes a cycle must not lower the count. The rootA != rootB check is what protects it.
    • Comparing parents instead of roots. Two nodes in the same group can have different parents. Only the roots tell you whether they are in the same group, so always call find first.
    • Updating the size of the wrong node. Add to size[rootA], the root that survives, and read sizes only at roots.
    • Isolated nodes. Nodes that appear in no edge, such as node 5 in the cycle example, still count. Starting components at n, not at 0, takes care of them.

    Testing

    Try these in the editor above. The results come from running the solution:

    nedgesResult
    5[[0, 1], [1, 2], [3, 4]]2
    6[[0, 1], [1, 2], [2, 0], [3, 4]]3
    4[]4
    1[]1
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free