Number of Provinces solution explained
Number of Provinces asks how many connected groups an n by n adjacency matrix describes, where linked[i][j] = 1 means cities i and j are directly connected. Start a DFS or BFS from every city that has not been reached yet and count how many times you start; each start discovers one whole province. Because the input is a matrix, visiting a city means scanning its full row, so the search is O(n²), which is also the size of the input. Union-find over the upper half of the matrix gives the same count.
By Evin JohnPublished 7 min read
Restating the problem
There are n cities. You get an n by n matrix where linked[i][j] is 1 if cities i and j have a direct road and 0 otherwise. The matrix is symmetric, and every city is linked to itself on the diagonal. A province is a largest set of cities where each can reach every other, directly or through other cities in the set. Return the number of provinces.
| City | Row of the matrix | Direct links |
|---|---|---|
| 0 | 1 1 0 0 0 | 1 |
| 1 | 1 1 0 0 0 | 0 |
| 2 | 0 0 1 0 1 | 4 |
| 3 | 0 0 0 1 0 | none |
| 4 | 0 0 1 0 1 | 2 |
Cities 0 and 1 form one province, 2 and 4 another, and city 3 stands alone, so the answer is 3. A city with no roads still counts as a province of one.
What the interviewer is checking
This is a connected-components question with an unusual input format. The interviewer wants to see that you treat cities as nodes and the matrix as the edges, that you do not confuse it with a grid problem where each cell is a node, and that you can state the cost correctly: with a matrix, finding a city's neighbours costs O(n) no matter how few roads it has. Many interviewers also ask for union-find as a second approach.
The grid mix-up is common enough to call out. In Number of Islands every cell of the grid is a node. Here, row i and column j are both cities, and a 1 at [i][j] is an edge between two nodes, not a piece of land.
Brute force: compute who can reach whom
Turn the matrix into a full reachability table with Warshall's algorithm: for each possible stop k, mark i as reaching j whenever i reaches k and k reaches j. After that, every province is a set of cities that all reach each other, and you can count each province once by its lowest-numbered city. This is O(n³) time and O(n²) space, far slower than a search, but easy to reason about and useful as a test reference.
def count_provinces_closure(linked):
n = len(linked)
reach = [[bool(linked[i][j]) or i == j for j in range(n)] for i in range(n)]
for k in range(n): # Warshall: allow k as a stop on the way
for i in range(n):
if reach[i][k]:
for j in range(n):
if reach[k][j]:
reach[i][j] = True
# each group is counted once, by its lowest-numbered city
return sum(1 for i in range(n) if not any(reach[i][j] for j in range(i)))Search from each unvisited city
Walk the cities in order. When you meet one that has not been visited, you have found a new province: add one to the count and run a search from it that visits every city it can reach. Cities reached by that search are skipped later, so each province is counted exactly once. The version below uses an explicit stack, so a long chain of cities cannot exhaust Python's recursion limit.
def count_provinces(linked):
n = len(linked)
seen = [False] * n
groups = 0
for city in range(n):
if seen[city]:
continue
groups += 1 # a city nobody reached yet starts a new group
seen[city] = True
stack = [city]
while stack:
cur = stack.pop()
for other in range(n): # scan the matrix row for direct links
if linked[cur][other] and not seen[other]:
seen[other] = True
stack.append(other)
return groupsOn the example, the loop starts at city 0 (count 1) and the search marks city 1. City 1 is skipped. City 2 starts a search (count 2) that marks city 4. City 3 starts a search (count 3) that finds nothing new. City 4 is already marked. The answer is 3.
Union-find
Begin with every city in its own group, so the count is n. Go through the matrix above the diagonal (it is symmetric, so the lower half adds nothing). For each 1, find the group of each city; if they differ, merge them and subtract one from the count. When the scan ends, the count is the number of provinces. Union by size keeps the trees shallow, and path halving shortens them further during each find.
function countProvinces(linked) {
const n = linked.length;
const parent = Array.from({ length: n }, (_, i) => i);
const size = new Array(n).fill(1);
const find = (x) => {
while (parent[x] !== x) {
parent[x] = parent[parent[x]]; // path halving
x = parent[x];
}
return x;
};
let groups = n;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) { // the matrix is symmetric, so half is enough
if (!linked[i][j]) continue;
let a = find(i);
let b = find(j);
if (a === b) continue;
if (size[a] < size[b]) [a, b] = [b, a];
parent[b] = a; // attach the smaller group under the larger
size[a] += size[b];
groups -= 1;
}
}
return groups;
}Union-find shines when the roads arrive one at a time and you need the province count after each one, because a search would have to start over each time. The same structure appears with weights in Evaluate Division and keyed by email in Accounts Merge.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Warshall closure | O(n³) | O(n²) |
| DFS or BFS from each unvisited city | O(n²) | O(n) |
| Union-find over the upper triangle | O(n² · α(n)) | O(n) |
| Search on an edge list instead of a matrix | O(n + E) | O(n + E) |
The last row is the useful follow-up: if the same graph came as a list of E roads, a search would cost O(n + E), which is much less than n² for a sparse map. The matrix format forces you to read all n² entries at least once, so nothing can beat O(n²) here.
Edge cases
- One city: one province.
- No roads at all: n provinces.
- Every city linked to every other: one province.
- A long chain where city i only links to i + 1, which is deep for recursive DFS.
- Links that only connect through a third city, such as 0 to 2 and 2 to 5.
Mistakes
- Treating the matrix as a grid of land and water and flood-filling cells.
- Counting the 1s, or counting the cities with at least one road.
- Counting a province every time the search visits a city, instead of once per search start.
- In union-find, decrementing the count even when the two cities were already in the same group.
- Recursive DFS in Python on large inputs without raising the limit or switching to a stack.
How to explain it out loud
Fictional example
- Candidate
- Each city is a node, and a one at row i, column j is an edge between city i and city j. So this is counting connected components.
- Candidate
- I'll loop over cities, and whenever one hasn't been visited, count a new province and run a DFS from it that marks everything it reaches.
- Interviewer
- Complexity?
- Candidate
- Each city is visited once, and visiting scans its row of n entries, so n squared, which is the size of the input anyway. Extra space is the visited array and the stack, both order n.
Related problems
Keys and Rooms is the directed cousin: one search from room 0 and a check that it reached everything. Open the Lock uses BFS for shortest distance rather than reachability. For a component count on a grid, see Number of Islands, and for ranges instead of graphs, Range Sum Query and Longest Increasing Path in a Matrix.
Practicing with Natively
If the matrix-versus-grid distinction keeps tripping you up, compare your reading with another one. Natively can read the problem from a screenshot on Mac or Windows and show its approach and code in an overlay, which makes the difference between nodes and cells easy to spot. Practicing with a partner, you can have it transcribe the session and then check how clearly you stated the O(n²) cost. More on the AI interview assistant.
Questions people ask
How do you solve Number of Provinces?
Treat cities as nodes and each 1 in the matrix as an edge. Start a DFS or BFS from every city not yet visited and count how many searches you start.
What is the time complexity of Number of Provinces?
O(n²) for n cities, because each city's row of n entries is scanned once. That is also the size of the input.
Can Number of Provinces be solved with union-find?
Yes. Start with n groups, and for every 1 above the diagonal merge the two cities' groups, subtracting one from the count when they were different.
How is Number of Provinces different from Number of Islands?
In Number of Islands each grid cell is a node. Here the matrix is an adjacency matrix: rows and columns are cities, and a 1 is a road between two of them.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
