← Uber bank

Uber · Question 45 · Graphs

Pacific Atlantic Water Flow

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

Problem

Given an m x n height matrix where water flows downhill, find all coordinates reaching both the Pacific (top/left) and Atlantic (bottom/right) oceans.

Approach

Reverse the flow: DFS/BFS uphill from each ocean's borders; intersect the reachable sets.

Time O(m×n)Space O(m×n)

How it works

  1. 1DFS uphill from Pacific borders and Atlantic borders.
  2. 2Mark every reachable cell per ocean.
  3. 3Cells reachable from both are the answer.

Sample input / output

Input:
5 5
1 2 2 3 5
3 2 3 4 4
2 4 5 3 1
6 7 1 4 5
5 1 1 2 4
Output:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]

Constraints

1 <= m, n <= 200; 0 <= heights <= 10^5.

Solution — read it, then walk it

Time O(m×n)Space O(m×n)Loops 5Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeat↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTheightsif not heights or notheights[0]RETURN []m, n = len(heights),len(heights[0])pac = [[False] * n for _ inrange(m)]atl = [[False] * n for _ inrange(m)]DEFINE dfs(r, c, visited,prev_height)if (r < 0 or r >= m orc < 0 or c >= n orvisited[r][c] orheights[r][c] <prev_height)RETURNvisited[r][c] = Truefor dr, dc in [(1, 0),(-1, 0), (0, 1), (0,-1)]dfs(r + dr, c + dc,visited, heights[r][c])for i in range(m)dfs(i, 0, pac,heights[i][0])dfs(i, n - 1, atl,heights[i][n - 1])for j in range(n)dfs(0, j, pac,heights[0][j])dfs(m - 1, j, atl,heights[m - 1][j])res = []for i in range(m)for j in range(n)if pac[i][j] andatl[i][j]res.append([i, j])RETURN resDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it))heights = [[int(next(it))for _ in range(n)] for _ inrange(m)]print(pacificAtlantic(heights))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/35

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