547. Number of Provinces - Detailed Explanation
Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!
Problem Statement
There are n cities numbered from 0 to n−1. You are given an n × n isConnected matrix where isConnected[i][j] = 1 if the iᵗʰ and jᵗʰ cities are directly connected, and isConnected[i][j] = 0 otherwise. A province is a group of directly or indirectly connected cities (an undirected connected component). Return the total number of provinces.
Examples
Example 1
Input
isConnected = [
[1,1,0],
[1,1,0],
[0,0,1]
]
Output
2
Explanation
Cities 0 and 1 are connected, forming one province; city 2 is isolated, forming a second.
Example 2
Input
isConnected = [
[1,0,0],
[0,1,0],
[0,0,1]
]
Output
3
Explanation
No two distinct cities are connected, so each forms its own province.
Constraints
- 1 ≤ n = isConnected.length = isConnected[i].length ≤ 200
- isConnected[i][i] = 1 for all i
- isConnected[i][j] = isConnected[j][i] ∈ {0,1}
Intuition
This is just counting connected components in an undirected graph given as an adjacency matrix. You can either:
- DFS/BFS from each unvisited city, marking all reachable cities as visited and incrementing your province count
- Union‑Find (Disjoint Set Union) to union every pair of directly connected cities, then count distinct roots
Depth‑First Search Approach
Explanation
- Maintain a visited array of size n.
- For each city i from 0…n−1, if it’s not visited, start a DFS to mark every city reachable from i.
- After each DFS, you’ve discovered one province, so increment count.
Algorithm
count = 0
visited = [false] * n
for i in 0…n−1:
if not visited[i]:
dfs(i)
count += 1
function dfs(u):
visited[u] = true
for v in 0…n−1:
if isConnected[u][v] == 1 and not visited[v]:
dfs(v)
Step‑by‑Step Walkthrough
isConnected = [
[1,1,0],
[1,1,0],
[0,0,1]
]
- i=0: not visited → dfs(0) marks 0, then sees v=1 is connected → dfs(1) marks 1. Returns → count=1
- i=1: already visited → skip
- i=2: not visited → dfs(2) marks 2 → count=2
Return 2
Union‑Find Approach
Explanation
- Initialize parent[i]=i for all i, and count = n (each city is its own province).
- For every pair (i,j) with isConnected[i][j]==1, union(i,j); if they had different roots, decrement count.
- At the end, count equals number of provinces.
Algorithm
parent[i] = i for i in 0…n−1
count = n
function find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
function union(a,b):
ra = find(a), rb = find(b)
if ra != rb:
parent[rb] = ra
count -= 1
for i in 0…n−1:
for j in i+1…n−1:
if isConnected[i][j] == 1:
union(i, j)
return count
Complexity Analysis
- Time
- DFS/BFS: O(n²) in worst case (adjacency‑matrix scan per node)
- Union‑Find: O(n² · α(n)) ≈ O(n²)
- Space
- O(n²) for input, O(n) extra for visited or parent arrays
Python Code
Python3
Python3
. . . .
Java Code
Java
Java
. . . .
Common Mistakes
- Forgetting to mark the starting city visited before recursing
- Only exploring
j=i+1
in DFS (must check all j=0…n−1) - In Union‑Find, not using path compression or merging both directions
Edge Cases
- n = 1 (single city) → return 1
- All cities fully connected → return 1
- No off‑diagonal connections → return n
Alternative Variations
- Number of Connected Components in an Undirected Graph (LeetCode 323) given adjacency list
- Friend Circles – same as this problem under a different name (Cracking the Coding Interview)
Related Problems
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-
GET YOUR FREE
Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.