Number of Provinces
Medium
Topics
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
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: grid = [[1,1,0],[1,1,0],[0,0,1]] Output: 2
Example 2
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
- Initialise each city as its own parent.
- For every pair
i < jwithgrid[i][j] == 1, union the two roots. - Count the distinct roots, calling
findon 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 2Complexity
- 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 ofpar[find(i)] = find(j). Linking the node rather than its root silently discards every union already recorded abovei. - Counting distinct entries of the parent array instead of distinct roots. Parent entries are stale until
findis called on them, so the count comes out too high. - Treating
grid[i][i] == 1as an edge. It is a self-loop the problem guarantees is always present; starting the inner loop ati + 1skips it for free. - Recursing in the DFS variant without noticing the depth can reach n. At
n <= 200that 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)))import java.util.*;
class Solution {
public int findCircleNum(int[][] grid) {
int n = grid.length;
int[] par = new int[n];
for (int i = 0; i < n; i++) par[i] = i;
for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (grid[i][j] == 1) par[find(par, i)] = find(par, j);
int cnt = 0;
for (int i = 0; i < n; i++) if (find(par, i) == i) cnt++;
return cnt;
}
int find(int[] par, int x) {
while (par[x] != x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findCircleNum(vector<vector<int>>& grid) {
int n = grid.size();
vector<int> par(n);
for (int i = 0; i < n; i++) par[i] = i;
function<int(int)> find = [&](int x) {
while (par[x] != x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
};
for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (grid[i][j] == 1) par[find(i)] = find(j);
int cnt = 0;
for (int i = 0; i < n; i++) if (find(i) == i) cnt++;
return cnt;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var findCircleNum = function(grid) {
const n = grid.length;
const par = [];
for (let i = 0; i < n; i++) par[i] = i;
const find = (x) => {
while (par[x] !== x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
};
for (let i = 0; i < n; i++) for (let j = i+1; j < n; j++) if (grid[i][j] === 1) par[find(i)] = find(j);
let cnt = 0;
for (let i = 0; i < n; i++) if (find(i) === i) cnt++;
return cnt;
};