Uber · Question 36 · Graphs
Number of Provinces
Problem
There are n cities. You are given an n x n matrix isConnected where isConnected[i][j] = 1 means city i and city j are directly connected, and 0 otherwise. A province is a group of directly or indirectly connected cities. Return the number of provinces.
Approach
Treat the matrix as an undirected graph. For each unvisited city, DFS through its connections and count one province.
Time O(n²)Space O(n)
How it works
- 1Treat each row as a city's adjacency list.
- 2DFS from every unvisited city, marking its province.
- 3Count one province per fresh DFS.
Sample input / output
Input: 3 1 1 0 1 1 0 0 0 1 Output: 2
Constraints
1 <= n <= 200; isConnected[i][i] == 1; symmetric matrix.
Solution — read it, then walk it
Time O(n²)Space O(n)Loops 2Branches 3Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/25
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits