← Meta (Facebook) bank

Meta (Facebook) · Question 61 · Graphs

Pacific Atlantic Water Flow

GraphsPythoncode⏱ O(mn)💾 O(mn)
Product-based

Problem

You are given m x n matrix representing heights. Find cells where water can flow to both oceans.

Approach

DFS uphill from both oceans' borders; the intersection reaches both.

Time O(mn)Space O(mn)

How it works

  1. 1DFS uphill from all Pacific border cells.
  2. 2Repeat from all Atlantic border cells.
  3. 3Cells in both sets reach both oceans.

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(mn)Space O(mn)Loops 4Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTheightsif not heightsRETURN []m, n = len(heights),len(heights[0])pacific = [[False] * n for_ in range(m)]atlantic = [[False] * n for_ in range(m)]DEFINE dfs(i, j, visited,prev)if (i < 0 or i >= m orj < 0 or j >= n orvisited[i][j] orheights[i][j] < prev)RETURNvisited[i][j] = Truedfs(i + 1, j, visited,heights[i][j])dfs(i - 1, j, visited,heights[i][j])dfs(i, j + 1, visited,heights[i][j])dfs(i, j - 1, visited,heights[i][j])for i in range(m)dfs(i, 0, pacific, -1)dfs(i, n - 1, atlantic, -1)for j in range(n)dfs(0, j, pacific, -1)dfs(m - 1, j, atlantic, -1)result = []for i in range(m)for j in range(n)if pacific[i][j] andatlantic[i][j]result.append([i, j])RETURN resultDEFINE 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/37

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