There are n cities. isConnected[i][j] is 1 when cities i and j are directly connected. A province is a group of cities connected directly or through other cities. Return the number of provinces.
Before you code
Start with every city in its own province. What happens to the count each time a union merges two different groups, and what happens when it doesn't?
Hints
- The matrix is symmetric, so only look at pairs with j greater than i.
- Start the count at n, and subtract 1 for every union that merges two different groups.
- Compare with a depth-first search solution: both are O(n²) here, since reading the matrix dominates.
Production & complexity notes
When solving Number of provinces on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Disjoint sets to reinforce the underlying pattern.
What it practices
Counting components with union-find, from Disjoint sets.