Back to Practice
#0288

Pacific Atlantic Water Flow

MediumDSA28 min20 XP

Problem

Water can flow from a cell to neighboring cells with height less than or equal to the current cell. Return sorted [row, col] cells that can reach both the Pacific top/left edges and Atlantic bottom/right edges.

Why This Matters

This problem teaches reverse traversal: start from the destinations instead of testing every source separately.

Function Signature

def pacific_atlantic(heights):

Examples

Example 1
Inputheights = [[1,2,2],[3,2,3],[2,4,5]]
Output[[0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

These cells can reach both ocean borders through non-increasing flow paths.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Small terrain
Input3 by 3 heights
Expected[[0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

Reverse traversal from each ocean finds the overlap.

One cell
Input[[7]]
Expected[[0, 0]]

The only cell touches both oceans.

Hidden Test Categories
flat gridstrictly increasing gridsingle row