Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
There are n cities, numbered 0 to n − 1. You get an n × n matrix isConnected where isConnected[i][j] = 1 means city i and city j have a direct road, and 0 means they don't. The matrix is symmetric, and every city is connected to itself (isConnected[i][i] = 1).
Roads chain together: if A connects to B and B connects to C, then A, B and C are all in the same province. Return the number of provinces. n is at most 200.
Example: [[1,1,0],[1,1,0],[0,0,1]] → 2. Cities 0 and 1 form one province, and city 2 is alone in another.
Start with brute force
The graph way works and is fine here: loop over cities, and whenever you find one you haven't visited, start a DFS from it, mark everything it reaches, and add one to the count. That's O(n²) because each DFS step scans a whole row of the matrix.
So this problem doesn't need a faster method. It's here because it is the cleanest possible place to learn Union-Find, a tool you'll need when the edges arrive one at a time and DFS would have to start over on every one. That happens in Redundant Connection and Swim in Rising Water.
Building the intuition
Forget the matrix for a moment and picture the cities as people at a party, all strangers. That's n separate groups.
Now someone reads out the friendships one by one: "0 and 1 are friends." Two groups become one, so the count drops from 3 to 2. "1 and 0 are friends" again: nothing changes, they're already together. "2 and 2": nothing.
So the whole answer is: start at n, and subtract one every time a road joins two groups that were separate. The only thing you need is a fast way to ask "are these two already in the same group?" and to merge two groups.
That's exactly what Union-Find (also called a disjoint set union, or DSU) does:
- Each group is a little tree. Its root is the group's "leader".
find(x)walks up fromxto its leader.union(a, b)finds both leaders. If they're the same, it returnsfalse. Otherwise it hangs one leader under the other and returnstrue.
Two tricks keep the trees almost flat (the Union-Find & Advanced Graphs primer explains why): path compression (after a find, point every node you walked past straight at the leader) and union by size (hang the smaller tree under the bigger one).
The optimal approach
- Build a DSU with
nnodes. Setprovinces = n. - For every pair
i < j(the matrix is symmetric, so the upper half is enough):- if
isConnected[i][j] == 1andunion(i, j)returnstrue, doprovinces -= 1.
- if
- Return
provinces.
The subtle detail is using the return value of union. A road between two cities that are already in the same province (like the third side of a triangle) must not lower the count. union returning false is how you know.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class DSU:
def __init__(self, n: int):
self.parent = list(range(n)) # every city starts as its own root
self.size = [1] * n
def find(self, x: int) -> int:
root = x
while self.parent[root] != root:
root = self.parent[root]
# path compression: point every node we walked past straight at the root
while x != root:
nxt = self.parent[x]
self.parent[x] = root
x = nxt
return root
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same group
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra # union by size: hang the smaller tree under the bigger
self.parent[rb] = ra
self.size[ra] += self.size[rb]
return True
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n = len(isConnected)
dsu = DSU(n)
provinces = n # start with n separate cities
for i in range(n):
for j in range(i + 1, n): # the matrix is symmetric, so the upper half is enough
if isConnected[i][j] == 1 and dsu.union(i, j):
provinces -= 1 # each successful merge joins two groups into one
return provincesclass DSU {
public:
vector<int> parent, sz;
DSU(int n) : parent(n), sz(n, 1) {
iota(parent.begin(), parent.end(), 0); // every city starts as its own root
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
// path compression: point every node we walked past straight at the root
while (x != root) {
int nxt = parent[x];
parent[x] = root;
x = nxt;
}
return root;
}
// "union" is a C++ keyword, so this one is called unite
bool unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (sz[ra] < sz[rb]) swap(ra, rb); // union by size: smaller tree under the bigger
parent[rb] = ra;
sz[ra] += sz[rb];
return true;
}
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
DSU dsu(n);
int provinces = n; // start with n separate cities
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // symmetric matrix: upper half is enough
if (isConnected[i][j] == 1 && dsu.unite(i, j)) {
provinces--; // each successful merge joins two groups
}
}
}
return provinces;
}
};class DSU {
int[] parent, size;
DSU(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i; // every city starts as its own root
size[i] = 1;
}
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
// path compression: point every node we walked past straight at the root
while (x != root) {
int nxt = parent[x];
parent[x] = root;
x = nxt;
}
return root;
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (size[ra] < size[rb]) { // union by size: smaller tree under the bigger
int t = ra; ra = rb; rb = t;
}
parent[rb] = ra;
size[ra] += size[rb];
return true;
}
}
class Solution {
public int findCircleNum(int[][] isConnected) {
int n = isConnected.length;
DSU dsu = new DSU(n);
int provinces = n; // start with n separate cities
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // symmetric matrix: upper half is enough
if (isConnected[i][j] == 1 && dsu.union(i, j)) {
provinces--; // each successful merge joins two groups
}
}
}
return provinces;
}
}class DSU {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i); // every city starts as its own root
this.size = new Array(n).fill(1);
}
find(x) {
let root = x;
while (this.parent[root] !== root) root = this.parent[root];
// path compression: point every node we walked past straight at the root
while (x !== root) {
const nxt = this.parent[x];
this.parent[x] = root;
x = nxt;
}
return root;
}
union(a, b) {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already in the same group
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra]; // union by size
this.parent[rb] = ra;
this.size[ra] += this.size[rb];
return true;
}
}
/**
* @param {number[][]} isConnected
* @return {number}
*/
var findCircleNum = function (isConnected) {
const n = isConnected.length;
const dsu = new DSU(n);
let provinces = n; // start with n separate cities
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) { // symmetric matrix: upper half is enough
if (isConnected[i][j] === 1 && dsu.union(i, j)) {
provinces--; // each successful merge joins two groups
}
}
}
return provinces;
};Dry run
isConnected = [[1,0,0,1],[0,1,1,0],[0,1,1,1],[1,0,1,1]] (roads: 0–3, 1–2, 2–3)
| Pair (i, j) | Road? | Leaders before | Merged? | provinces |
|---|---|---|---|---|
| start | each city is its own leader | 4 | ||
| (0, 1) | no | 4 | ||
| (0, 2) | no | 4 | ||
| (0, 3) | yes | 0 and 3 | yes, 3 goes under 0 | 3 |
| (1, 2) | yes | 1 and 2 | yes, 2 goes under 1 | 2 |
| (1, 3) | no | 2 | ||
| (2, 3) | yes | find(2) = 1, find(3) = 0 | yes, sizes tie so 0 goes under 1 | 1 |
All four cities end up with leader 1: one province.
Complexity
- Time: O(n² · α(n)). We look at about n²/2 matrix cells, and each union costs α(n), the inverse Ackermann function. It is at most 4 for any input that fits in the universe, so treat it as a constant. Reading the matrix is O(n²) anyway, so you can't beat this.
- Space: O(n) for the
parentandsizearrays.
Edge cases and traps
- Counting every 1 in the matrix. A triangle 0–1–2 has three roads but only two of them merge anything. Count successful unions, not ones.
- Forgetting the diagonal is all 1s.
union(i, i)is harmless (it returnsfalse), but loopingjfromi + 1skips it anyway. - A
findthat only walks up. Without path compression and union by size, a chain of unions can build a tall tree, and eachfindbecomes O(n). unionas a name in C++. It's a keyword there, so the C++ version calls itunite.
Say it in the interview
"A province is a connected component. I'll use Union-Find: every city starts as its own group, so the count starts at n. I scan the upper half of the matrix, and for every road I union the two cities. If the union actually merged two different groups, the count drops by one. With path compression and union by size each operation is effectively constant, so it's O(n²) to read the matrix and O(n) extra space. A DFS counting components would also work in O(n²)."
Follow-ups interviewers ask
- "Could you do it with DFS or BFS?" Yes: for each unvisited city, flood-fill from it and add one. Same O(n²) here. Union-Find wins when roads arrive one at a time, because DFS would need to rerun.
- "What if the input were an edge list instead of a matrix?" Same code, but loop over the edges: O(E · α(n)) instead of O(n²). That's Number of Operations to Make Network Connected.
- "What if cities could also lose roads?" Union-Find can't split groups. The usual trick is to process the deletions in reverse, as additions.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free