mediumUnion FindGraphUnion Find

Number of Provinces

mediumTime: O(n^2 * α(n))Space: O(n)

Recognize the pattern

count friend groupsadjacency matrixconnected components

Brute force idea

The naive version of Number of Provinces sounds like this: DFS/BFS from each unvisited node. Traverses the adjacency matrix. 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

The real unlock in Number of Provinces comes when you notice this: Union-Find: for each pair (i,j) where isConnected[i][j] = 1, union(i,j). Count distinct roots. — still for reading the matrix, but Union-Find is cleaner for connectivity. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Number of Provinces is this: Each connected component = one province. If i and j are connected (directly or transitively), they're in the same province. Union-Find tracks this transitivity automatically. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

The trap in Number of Provinces usually looks like this: Only checking direct connections — friend-of-friend is the same province. Union-Find handles transitivity; BFS/DFS does too via traversal. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Union Find Pattern