Number of Provinces
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Number of Provinces
Given an matrix
isConnected where isConnected[i][j] = 1 if city and city are directly connected. Return the total number of provinces (connected components).Examples
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Approach 1
Level I: DFS (Component Counting)
Intuition
Treat the matrix as an adjacency list. For each city, if not visited, start a DFS to visit all cities in its province. Count the number of DFS starts.
⏱ O(N^2)💾 O(N)
Detailed Dry Run
City 0: unvisited. Count=1. DFS(0) visits City 1. City 1: visited. City 2: unvisited. Count=2. DFS(2).
Approach 2
Level III: Union-Find (Component ID)
Intuition
Standard DSU application. For every connection, perform a union. The answer is the initial city count minus successful unions.
⏱ O(N^2 \cdot \alpha(N))💾 O(N)
Detailed Dry Run
3 Cities. Initial count=3. Union(0,1) -> success, count=2. Connection(0,2)=0 -> no union. Connection(1,2)=0 -> no union.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.