Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Graphs

Number of Connected Components In An Undirected Graph

MEDIUM✓ CHIP-TIMEDLC #323 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Given n nodes labeled 0 to n−1 and a list of undirected edges between them, count how many separate clusters the nodes split into — where a cluster is any group reachable from each other through the given edges.

A set of n nodes labeled 0 through n−1 arrives with a list of undirected edges connecting some of them. The task is to count how many separate clusters the nodes end up split into, where a cluster is any group reachable from each other through those edges.

A node with no edges at all still counts as its own cluster of one — nothing in the input guarantees every node touches an edge, so isolated nodes are entirely possible and expected.

The answer is a single number: the count of distinct clusters once every edge has been accounted for, whether that's one big connected graph or many small disconnected pieces.

  • up to a few thousand nodes and edges
  • edges are undirected, and a pair may only appear once
  • a node with no edges still forms its own one-node cluster
  • answer is a single integer cluster count
EX 01
n = 5 · edges = [[0, 1], [1, 2], [3, 4]]
→ 2
a chain of three and a pair
EX 02
n = 5 · edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
→ 1
one chain spans all five
EX 03
n = 1 · edges = []
→ 1
a single node is its own cluster

The hintstake only what you need

HINT 1 THE NUDGE

Nodes with no path between them belong to different clusters, no matter how the edge list happens to be ordered. What operation merges two nodes into the same cluster the instant an edge connects them?

HINT 2 THE STRUCTURE

Start by assuming every node is its own cluster — n of them. Each edge either joins two clusters that were still separate, or reconnects two nodes already in the same one and changes nothing.

HINT 3 ONE STEP FROM THE ANSWER

Union-Find each edge's endpoints, and only decrement a running cluster count when the union actually merges two different roots. Whatever count is left when every edge is processed is the answer.

Coach's boardthe pattern, step by step

COUNTING THE CLUSTERSPATTERN · UNION-FINDn = 5 · edges: (0,1) (1,2) (3,4)
STEP 1

5 nodes start as 5 separate clusters. Every union that actually merges two different clusters shrinks that count by one.

STEP 1 / 5 · ← → WORK TOO

The splitstwo paces, two languages

grind/number-of-connected-components-in-an-undirected-graph.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        parent = list(range(n))

        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        components = n
        for a, b in edges:
            ra, rb = find(a), find(b)
            if ra != rb:
                parent[ra] = rb
                components -= 1
        return components
TIME O(V+E·Α(V))SPACE O(V)PYTHON · RACE PACE · 17 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED