Number of Provinces

medium

There are n cities, some connected directly. You are given an n × n matrix isConnected where isConnected[i][j] == 1 means city i and city j are directly connected (the matrix is symmetric and the diagonal is 1). A province is a group of cities connected directly or indirectly. Return the total number of provinces.

Hints

Treat each row of the matrix as a city's neighbour list.
A province is a connected component — flood each unvisited city.
Union-Find alternative: union every pair (i, j) with isConnected[i][j] == 1.

Common doubts

The graph is given as an n×n matrix, so just reading it — finding each city's neighbours — costs n² regardless of the algorithm.
Yes — it's the same problem; you just derive neighbours by scanning matrix rows instead of a stored list.
The matrix is symmetric, so the lower triangle repeats the upper; scanning half avoids redundant unions.

Interview follow-ups

Store it as an adjacency list instead, dropping the cost from O(n²) to O(n + edges).
Track component sizes during the flood or with a size array in union-find.

Fun facts

  • This is LeetCode 547 — the matrix-flavoured twin of counting connected components.
  • The 'friend circles' framing is the same problem with people instead of cities.

Asked at

AmazonMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Cities 0 and 1 form one province; city 2 is another.
Example 2
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
No connections, so three provinces.
Constraints

- 1 <= n <= 200 - isConnected[i][j] is 0 or 1 - isConnected[i][i] == 1 - isConnected[i][j] == isConnected[j][i]

Solve this problem →