InterviewPrepKit

Home / Coding / Graphs

Number of Provinces

medium Original ↗
Solving tips
  • A province is a connected component and isConnected is an adjacency matrix: neighbors of city i are the columns j where isConnected[i][j]==1.
  • Count fresh DFS/BFS starts over unvisited cities, or union every connected pair and count remaining sets; O(n^2) is forced because the dense matrix must be fully read.
  • In union-find iterate only j>i to skip the symmetric lower triangle and the all-1s diagonal (self-loops).
  • Pitfall: it's an adjacency matrix, not an edge list of literal [i,j] pairs, and only a successful merge should decrement the province count.

Problem

There are n cities. Some are directly connected, others aren’t. A province is a group of cities that are directly or indirectly connected, with no connections to cities outside the group.

You’re given an n x n matrix isConnected where isConnected[i][j] = 1 means city i and city j are directly connected, and 0 means they aren’t. The matrix is symmetric (isConnected[i][j] == isConnected[j][i]) and its diagonal is all 1s (a city is connected to itself).

Return the number of provinces.

Examples

  • isConnected = [[1,1,0],[1,1,0],[0,0,1]]2 — cities 0 and 1 are directly connected (one province), city 2 is alone (another).
  • isConnected = [[1,0,0],[0,1,0],[0,0,1]]3 — no city connects to any other, so three provinces.
  • isConnected = [[1,1,0],[1,1,1],[0,1,1]]1 — 0–1 and 1–2 are connected, so 0,1,2 form a single province via city 1.

Constraints

  • 1 <= n <= 200
  • isConnected[i][j] is 0 or 1; the matrix is symmetric with isConnected[i][i] = 1.

Think about it first

Hint 1 A province is a connected component of the "cities" graph. The `isConnected` matrix is an adjacency matrix: row `i` tells you which cities `i` touches directly.
Hint 2 Walk over the cities. Each city you haven't visited begins a new province: DFS or BFS to mark every city reachable through direct/indirect connections, then move on. The number of traversals you start is the answer.
Hint 3 Union-find is a clean fit: for every pair `i < j` with `isConnected[i][j] == 1`, union `i` and `j`. Start the province count at `n` and decrement on each successful merge.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.