Number of Connected Components in an Undirected Graph

Medium

Topics
GraphUnion FindDFSBFS

Given n nodes labeled 0..n-1 and a list of undirected edges, return the number of connected components.

Example 1

01234
Each shade is one connected component: a group of nodes reachable from one another. Isolated nodes count too, which is the usual off-by-one. There are 2.
Nodes are drawn on a circle; an edge list says nothing about layout, only about connections.
Input:  n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2

Example 2

01234
Input:  n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
Editorial — intuition, approach, complexity and pitfalls

Intuition

Start with n isolated components. Each edge that joins two different components reduces the count by one — that is exactly what union-find tracks.

Approach

  1. Initialize a DSU with each node its own parent and a component count of n.
  2. For each edge, union the endpoints; if they were in different sets, decrement the count.
  3. Return the final count.

Dry Run

n = 5, edges 0-1 1-2 3-4
Start by assuming the worst: every node is its own component.
  comp = 5    par [0, 1, 2, 3, 4]
  edge 0-1   roots 0 and 1 differ  ->  merge, comp = 4   par [1, 1, 2, 3, 4]
  edge 1-2   roots 1 and 2 differ  ->  merge, comp = 3   par [1, 2, 2, 3, 4]
  edge 3-4   roots 3 and 4 differ  ->  merge, comp = 2   par [1, 2, 2, 4, 4]
answer 2   --  {0, 1, 2} and {3, 4}
Counting down from n rather than up from 0 is what avoids a second pass. Every
successful union reduces the count by exactly one, because it replaces two
components with one; no traversal is needed at the end to find out how many
survived.
The `ra != rb` guard is the part that has to be right. An edge whose endpoints are
already in the same component merges nothing, so decrementing for it counts a
merge that never happened. Drop the guard and two isolated nodes with the
self-loops 0-0 and 1-1 report 0 components instead of 2.
Path compression inside find -- `par[x] = par[par[x]]` -- is what keeps this near
linear. Without it a chain of unions degrades into a linked list and every find
walks its whole length.

Complexity

  • Time — O((V+E) alpha): near-constant union-find operations.
  • Space — O(V): the parent array.

Common Pitfalls

  • Only decrement when the roots actually differ. A self-loop or a repeated edge otherwise counts as a merge that never happened: two isolated nodes with edges 0-0 and 1-1 report 0 components instead of 2.
  • Path compression in find is what keeps this near-linear. Without it a chain of unions degrades to a linked list and each find walks it.

Full Solution — all languages

class Solution:
    def countComponents(self, n, edges):
        par=list(range(n))
        def find(x):
            while par[x]!=x:
                par[x]=par[par[x]]; x=par[x]
            return x
        comp=n
        for a,b in edges:
            ra,rb=find(a),find(b)
            if ra!=rb: par[ra]=rb; comp-=1
        return comp
SensAI
Beta
Tap the mic to stop voice mode