15% off all plans & roadmaps Use code
See plansLeetCode 547 · Solution & editorial
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
Number of Provinces is a Graph Traversal Patterns (DFS & BFS) problem, in the Graph DFS - Connected Components / Island Counting subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Use DFS to find connected components and count islands in grids. Flood fill and province counting problems.
The reference solution runs in O(n^2) time and O(n) space.
Number of Provinces has been reported in interviews at Amazon, Two Sigma, Goldman Sachs, Dropbox, Facebook, Audible.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Number of Provinces is a Graph Traversal Patterns (DFS & BFS) problem, in the Graph DFS - Connected Components / Island Counting subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.