InterviewPrepKit

Home / Coding / Graphs

Pacific Atlantic Water Flow

medium Original ↗
Solving tips
  • Key insight: don't search forward from every cell (O((m*n)^2)); reverse the flow and search inland from each ocean's border once, then intersect the two reachable sets.
  • On the reversed climb, step to a neighbor only when its height is >= current (the reverse of downhill flow); use <= / >= so equal heights are passable both ways.
  • Seed a multi-source DFS/BFS with all border cells of an ocean at once, giving O(m*n) time and space per ocean.
  • Pitfall: corner cells legitimately belong to both oceans' borders, so seed all four edges; the answer is the intersection of the Pacific-reachable and Atlantic-reachable sets.

Problem

You’re given an m x n grid heights where heights[r][c] is the height of a cell. The Pacific Ocean touches the top edge and the left edge of the grid; the Atlantic Ocean touches the bottom edge and the right edge.

Water can flow from a cell to a neighbor (up/down/left/right) if the neighbor’s height is less than or equal to the current cell’s height. Water can flow off the grid into an ocean from any cell on that ocean’s border.

Return a list of all cells [r, c] from which water can reach both the Pacific and the Atlantic.

Examples

  • heights = [[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]][[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] — each listed cell can drain to both oceans (order may vary).
  • heights = [[1]][[0,0]] — a single cell touches every border, so it reaches both oceans.
  • heights = [[2,1],[1,2]][[0,0],[0,1],[1,0],[1,1]] — every cell can reach both oceans here.

Constraints

  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 10^5
  • “Flow” is allowed to an equal-or-lower neighbor; ties count.

Think about it first

Hint 1 Doing a separate search from every cell to test "can this reach the ocean?" is O((m·n)²). Flip the question: instead of water flowing *down and out*, imagine it climbing *inland from each ocean*.
Hint 2 From an ocean's border cells, do a traversal that moves to a neighbor only if that neighbor is **higher or equal** (reverse of the real flow). Every cell you reach is a cell that could drain *into* that ocean. Run this once from the Pacific border and once from the Atlantic border.
Hint 3 You get two sets: cells reachable from the Pacific and cells reachable from the Atlantic. The answer is their intersection. Multi-source DFS or BFS seeded with all border cells at once does each ocean in one pass.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.