PROBLEM 44 OF 75

Number of Connected Components in an Undirected Graph

Count connected components among n nodes and undirected edges.

PATTERNGraphs: traversal & orderingNodes are facts; edges are allowed moves.
SPOT THE SIGNAL

Why does this pattern fit?

FRAME · 1 OF 4

Restate the exact job

Count connected components among n nodes and undirected edges.

WHY THIS FITS

Every successful union merges two components.

COMPLEXITY

O((V + E) α(V)) time · O(V) space

COMMON FAILURE

Decrementing for redundant edges undercounts components.

THE REASONING, IN ONE PLACE

How to solve Number of Connected Components in an Undirected Graph

The goal is to solve this problem from the pattern, not to memorize a finished answer. Use this as a check after your own attempt.

What the question asks

Count connected components among n nodes and undirected edges.

Why Graphs: traversal & ordering fits

Every successful union merges two components.

State to maintain

A disjoint-set parent/rank structure and component count.

Transition

Union endpoints; decrement count only when roots were different.

Time and space

O((V + E) α(V)) time · O(V) space

Counterexample to the tempting mistake

Decrementing for redundant edges undercounts components.

Prove it again tomorrow

Close this page. Rebuild the state and transition from memory, write a test that exposes the mistake above, then solve a fresh input without looking back. A same-day reread is practice, not proof of retention.

Open blank recall ↗