Number of Connected Components in an Undirected Graph
Count connected components among n nodes and undirected edges.
Why does this pattern fit?
Restate the exact job
Count connected components among n nodes and undirected edges.
Every successful union merges two components.
O((V + E) α(V)) time · O(V) space
Decrementing for redundant edges undercounts components.
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.