Number of Provinces
Count groups of directly or indirectly connected cities by merging them with union-find.
The problem
There are n cities, and isConnected[i][j] is 1 when cities i and j are directly connected and 0 otherwise. Connections carry over: if a is connected to b and b to c, then a and c are in the same group. Such a group is a province; return the number of provinces.
Input isConnected = [[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]
Output 2
Cities 0 and 3 form one province, and cities 1 and 2 form the other.
Input isConnected = [[1, 1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]
Output 3
0 and 2 are not linked directly, but both are linked to 1, so 0, 1 and 2 share a province. Cities 3 and 4 are on their own.
How to spot the pattern
- You need the number of connected groups, not paths or distances.
- Connections come as pairs, and each pair simply joins two groups.
The idea
Start with every city in its own province, so there are n provinces. Each connection merges the provinces of its two cities, unless they are already in the same one, and union-find does both the check and the merge in nearly O(1). Every merge that actually happens lowers the count by one, and the count left at the end is the answer.
Brute force: Give each city a group label and, on every merge, relabel all cities of one group, which costs O(n) per merge instead of nearly O(1).
Step by step
- 1Give every city its own group (
parent[i] = i, size 1) and set the count ton. - 2Write
find(x), which follows parent links up to the group's root and shortens the path on the way. - 3Write
union(x, y), which finds both roots, returns false if they are the same, and otherwise hangs the smaller group under the larger one. - 4For every pair
i < jwithisConnected[i][j] == 1, callunion(i, j)and lower the count when it merges two groups. - 5Return the count.
See the pattern move
The union-find pattern on a small example. Step through it, or press play.
Code
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n = len(isConnected)
parent = list(range(n)) # every city starts as its own group
group_size = [1] * n
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving: point to the grandparent
x = parent[x]
return x
def union(x: int, y: int) -> bool:
a, b = find(x), find(y)
if a == b:
return False # already one group
if group_size[a] < group_size[b]:
a, b = b, a
parent[b] = a # hang the smaller group under the larger one
group_size[a] += group_size[b]
return True
provinces = n
for i in range(n):
for j in range(i + 1, n):
if isConnected[i][j] == 1 and union(i, j):
provinces -= 1 # two provinces became one
return provincesComplexity
Time
O(n^2)
Space
O(n)
Every matrix entry is read once; with path compression and union by size each find is nearly O(1) (inverse Ackermann time), and the parent and size arrays hold n entries.
Watch out for
- Lowering the count for every connected pair, even when the two cities are already in one group.
- Comparing
iandjthemselves instead of their roots, which misses indirect connections. - Skipping union by size and path compression, which lets the parent links grow into long chains and makes each find O(n).
Follow-up questions
Can you solve it with DFS instead?
Yes. Start a DFS from each city that has not been visited, mark everything it reaches, and count how many DFS runs you started. On the matrix it is also O(n^2).
When is union-find the better choice?
When connections arrive one at a time and you need the count after each one, or when you only have a list of pairs and never need to walk the graph. Each new pair costs nearly O(1) instead of a new search.
In Hinglish
Shuru mein har city apne alag group mein hai. Har connection par dono ke root nikalo; root alag hain toh groups jodo aur count ek kam karo.