Number of Connected Components
Recognize the pattern
Brute force idea
The naive version of Number of Connected Components sounds like this: For each unvisited node, DFS/BFS to find its component. This IS the standard approach; Union-Find offers a different angle. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
Better approach
A calmer way to see Number of Connected Components is this: Union-Find: initially each node is its own component. For each edge, union the two nodes. Count the number of distinct roots at the end. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Key invariant
The compass for Number of Connected Components is this: Two nodes in the same component share the same root in the Union-Find structure. The number of distinct roots = number of connected components. As long as that statement keeps holding, you can trust the steps built on top of it.
Watch out for
A common way to get lost in Number of Connected Components is this: Forgetting path compression and union by rank — without them, Union-Find degrades to per operation. With both optimizations, it's nearly amortized. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.