mediumUnion FindGraphUnion Find

Number of Provinces

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

Signals to notice

count friend groupsadjacency matrixconnected components

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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