Number of Provinces

Medium

Topics
GraphDFSBFSUnion Find

There are n cities. You are given an n x n matrix grid where grid[i][j] = 1 means city i and city j are directly connected. A province is a group of directly or indirectly connected cities. Return the total number of provinces.

Example 1

012
The input is an adjacency matrix, not an edge list: isConnected[i][j] = 1 means a direct road. Drawn as a graph, each shade is one province — a connected group of cities. There are 2.
Input is an n×n adjacency matrix; the figure shows the graph it describes.
Input:  grid = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2

Example 2

012
Input:  grid = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3

Constraints

  • 1 <= n <= 200
  • grid[i][j] is 1 or 0
  • grid[i][i] == 1
  • grid[i][j] == grid[j][i].
Editorial — intuition, approach, complexity and pitfalls

Intuition

This is counting connected components, with the graph handed over as an adjacency matrix. Either union-find or a depth-first search from each unvisited city answers it.

The thing worth saying out loud is that the matrix sets the bound. Reading it is Θ(n²) no matter what, so the choice of component algorithm cannot improve the complexity — it only changes the constant. Candidates often present union-find as the optimisation; it is not, and claiming otherwise invites a question you will lose.

Approach

  1. Initialise each city as its own parent.
  2. For every pair i < j with grid[i][j] == 1, union the two roots.
  3. Count the distinct roots, calling find on each city so no stale parent is counted.

Dry Run

grid = [[1,1,0],
        [1,1,0],
        [0,0,1]]

parent start  [0, 1, 2]

grid[0][1] = 1  ->  union(0,1): root 0 now points at 1   parent [1, 1, 2]
grid[0][2] = 0  ->  skip
grid[1][2] = 0  ->  skip

final roots  [1, 1, 2]  ->  2 distinct

answer 2

Complexity

  • Time — Θ(n²): the matrix scan dominates and is unavoidable. The union-find operations add an amortised per-operation factor on top: the shown code uses path halving without union by size, which gives O(log n) amortised, and adding union by size would bring it to the inverse-Ackermann α(n). Either way the n² scan is the bound.
  • Space — O(n) for the parent array. A DFS version is also O(n) for the visited array plus up to O(n) of recursion depth.

Common Pitfalls

  • Quoting α(n) while implementing path compression alone. Union by size or rank is the other half of that guarantee; with only one of the two the amortised bound is O(log n).
  • Scanning the whole matrix including j < i. The matrix is symmetric, so the upper triangle is enough — half the work, same bound.
  • Writing par[i] = find(j) instead of par[find(i)] = find(j). Linking the node rather than its root silently discards every union already recorded above i.
  • Counting distinct entries of the parent array instead of distinct roots. Parent entries are stale until find is called on them, so the count comes out too high.
  • Treating grid[i][i] == 1 as an edge. It is a self-loop the problem guarantees is always present; starting the inner loop at i + 1 skips it for free.
  • Recursing in the DFS variant without noticing the depth can reach n. At n <= 200 that is safe, but the same code on a grid problem with 250,000 cells is not — see number of enclaves.

Full Solution — all languages

class Solution:
    def findCircleNum(self, grid):
        n = len(grid)
        par = list(range(n))
        def find(x):
            while par[x] != x:
                par[x] = par[par[x]]; x = par[x]
            return x
        for i in range(n):
            for j in range(i+1, n):
                if grid[i][j] == 1:
                    par[find(i)] = find(j)
        return len(set(find(i) for i in range(n)))
Asked at Pinterest Two Sigma
SensAI
Beta
Tap the mic to stop voice mode