← Uber bank

Uber · Question 34 · Graphs

Number of Islands

GraphsPythoncode⏱ O(m*n)💾 O(m*n)
Product-based

Problem

Given a 2D grid of ‘1’s (land) and ‘0’s (water), count the number of islands (connected components of land).

Approach

Use BFS (or DFS) to traverse connected lands. Mark visited cells to avoid recounting. (BFS)

Time O(m*n)Space O(m*n)

How it works

  1. 1Scan every cell; each fresh '1' starts an island.
  2. 2BFS floods the whole island, sinking cells to '0'.
  3. 3Count one per flood; sunk cells never recount.

Sample input / output

Input:
4 5
11000
11000
00100
00011
Output:
3

Constraints

1 <= m, n <= 300; cells are '0' (water) or '1' (land).

Solution — read it, then walk it

Time O(m*n)Space O(m*n)Loops 5Branches 5Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyes↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINE numIslands(grid:list) -> intif not gridRETURN 0rows, cols = len(grid),len(grid[0])DEFINE neighbors(r, c)for nr, nc in [(r - 1,c), (r + 1, c), (r, c- 1), (r, c + 1)]if 0 <= nr < rows and0 <= nc < colsyield nr, nccount = 0for r in range(rows)for c in range(cols)if grid[r][c] == '1'count += 1queue = deque([(r, c)])grid[r][c] = '0'while queuecr, cc = queue.popleft()for nr, nc inneighbors(cr, cc)if grid[nr][nc] == '1'queue.append((nr, nc))grid[nr][nc] = '0'RETURN countDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it))grid = [[c for c innext(it)] for _ inrange(m)]print(numIslands(grid))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/33

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