There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

Return the total number of provinces.

Input & Output

Example 1 — Two Separate Provinces
$ Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
💡 Note: Cities 0 and 1 are connected (province 1). City 2 is isolated (province 2). Total: 2 provinces.
Example 2 — All Connected
$ Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
💡 Note: No connections between cities. Each city is its own province: 0, 1, 2. Total: 3 provinces.
Example 3 — Chain Connection
$ Input: isConnected = [[1,1,0],[1,1,1],[0,1,1]]
Output: 1
💡 Note: City 0↔1, City 1↔2, so all cities are in one connected province. Total: 1 province.

Constraints

  • 1 ≤ n ≤ 200
  • n == isConnected.length
  • n == isConnected[i].length
  • isConnected[i][j] is 1 or 0
  • isConnected[i][i] == 1
  • isConnected[i][j] == isConnected[j][i]

Visualization

Tap to expand
Number of Provinces - Union-Find Solution INPUT isConnected Matrix (n=3) 0 1 2 1 1 0 row 0 1 1 0 row 1 0 0 1 row 2 Cities as Graph: 0 1 2 Blue = Connected, Red = Isolated ALGORITHM STEPS 1 Initialize Union-Find parent[i] = i, rank[i] = 0 parent: 0 1 2 2 Process Connections For each isConnected[i][j]=1 where i < j, union(i, j) 3 Union Operations union(0,1): merge cities 0,1 parent: 0 0 2 4 Count Provinces Count nodes where parent[i] == i (roots) Roots: 0 2 2 roots = 2 provinces FINAL RESULT Identified Provinces: Province 1 0 1 Province 2 2 Output: 2 OK - Verified! 2 disjoint sets found Time: O(n^2 * alpha(n)) Space: O(n) Key Insight: Union-Find efficiently tracks connected components. Each city starts as its own set. When we find a connection, we union the sets. The number of provinces equals the count of distinct roots (nodes where parent[i] == i). Path compression and union by rank ensure near O(1) operations. TutorialsPoint - Number of Provinces | Union-Find (Disjoint Set) Approach
Asked in
Amazon 45 Facebook 32 Google 28 Microsoft 22
67.0K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen