← Uber bank

Uber · Question 36 · Graphs

Number of Provinces

GraphsPythoncode⏱ O(n²)💾 O(n)
Product-based

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

  1. 1Treat each row as a city's adjacency list.
  2. 2DFS from every unvisited city, marking its province.
  3. 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.
yes↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTisConnectedn = len(isConnected)visited = [False] * nDEFINE dfs(i)for j in range(n)if isConnected[i][j]== 1 and notvisited[j]visited[j] = Truedfs(j)provinces = 0for i in range(n)if not visited[i]visited[i] = Truedfs(i)provinces += 1RETURN provincesDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))isConnected =[[int(next(it)) for _ inrange(n)] for _ i…print(findCircleNum(isConnected))if __name__ =="__main__"main()END
  • 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