Pacific Atlantic Water Flow solution explained

Pacific Atlantic Water Flow gives a grid of land heights with one ocean along the top and left edges and another along the bottom and right, and asks which cells can drain rainwater into both oceans, where water moves to a neighbor of equal or lower height. Instead of following water downhill from every cell, search uphill from each coastline: one search marks every cell that can reach the first ocean, a second marks the cells that can reach the other, and the answer is the cells marked by both. That takes O(rows × cols) time.

By Published 9 min read

The problem

You get a rectangular map where each cell holds a height. The Pacific borders the map's top edge and left edge; the Atlantic borders the bottom edge and right edge. Rain on a cell can run to any of its four neighbors whose height is less than or equal to its own, and from there keep going by the same rule. A cell on an edge drains straight into the ocean along that edge. Return the coordinates of every cell from which rain can reach both oceans.

        Pacific (top and left)
     3   3   4   5*
     2   4   5*  3
     1   5*  2   2
     4*  3   1   1
        Atlantic (bottom and right)

answer: (0,3) (1,2) (2,1) (3,0)
A height map made up for this page. Cells marked * reach both oceans.

The top-right and bottom-left corners always qualify, because each sits on one Pacific edge and one Atlantic edge. The two cells of height 5 in the middle form a ridge: from (1,2), water can run north to (0,2), height 4, which sits on the top edge, or right to (1,3), height 3, which sits on the right edge. The cell (1,1) with height 4 reaches the Pacific easily but is boxed in by the 5s on its Atlantic side, so it does not qualify.

Confirm two details: water moves to neighbors that are lower or equal, so flat stretches let water pass in both directions; and the order of the output usually does not matter.

What it reveals in an interview

Many candidates can write a flood fill. Fewer think to run it backward. The problem is built to reward that switch: the forward question (where does water from here end up?) is expensive to ask for every cell, while the reverse question (which cells can send water to this coast?) is one search per coast. Interviewers often let a candidate start with the brute force and wait to see whether they spot the reversal themselves.

Brute force: follow the water from every cell

For each cell, run a search that moves only to neighbors of equal or lower height, and note whether it touches a Pacific edge and an Atlantic edge. If it touches both, keep the cell. Each search can visit the whole map, so the total is O((R·C)²). It is a fine reference to test against and a reasonable first sentence in the interview, as long as you move on quickly.

def both_oceans_slow(heights):
    h = len(heights)
    w = len(heights[0]) if h else 0
    found = []
    for r in range(h):
        for c in range(w):
            seen, stack = {(r, c)}, [(r, c)]
            pacific = atlantic = False
            while stack:
                x, y = stack.pop()
                pacific |= x == 0 or y == 0
                atlantic |= x == h - 1 or y == w - 1
                for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
                    if (0 <= nx < h and 0 <= ny < w and (nx, ny) not in seen
                            and heights[nx][ny] <= heights[x][y]):
                        seen.add((nx, ny))
                        stack.append((nx, ny))
            if pacific and atlantic:
                found.append([r, c])
    return found
Python reference: a downhill search from each cell. Used to check the fast version.

The efficient approach: climb from each coast

Reverse every move. If water can run from cell A down to neighbor B, then going backward, B can be climbed to A, which is allowed when A is at least as high as B. Seed one search with every cell on the top and left edges; let it step to any neighbor that is equal or higher; everything it reaches can drain to the Pacific. Seed a second search with every cell on the bottom and right edges for the Atlantic. Cells reached by both searches are the answer.

from collections import deque


def pacific_atlantic(heights):
    if not heights or not heights[0]:
        return []
    h, w = len(heights), len(heights[0])

    def climb(sources):
        reach = [[False] * w for _ in range(h)]
        queue = deque()
        for r, c in sources:
            if not reach[r][c]:
                reach[r][c] = True
                queue.append((r, c))
        while queue:
            r, c = queue.popleft()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if (0 <= nr < h and 0 <= nc < w and not reach[nr][nc]
                        and heights[nr][nc] >= heights[r][c]):
                    reach[nr][nc] = True
                    queue.append((nr, nc))
        return reach

    pac = climb([(0, c) for c in range(w)] + [(r, 0) for r in range(h)])
    atl = climb([(h - 1, c) for c in range(w)] + [(r, w - 1) for r in range(h)])
    return [[r, c] for r in range(h) for c in range(w) if pac[r][c] and atl[r][c]]
Python: two multi-source breadth-first searches that climb, then an intersection.
function pacificAtlantic(heights) {
  const h = heights.length;
  if (h === 0 || heights[0].length === 0) return [];
  const w = heights[0].length;
  const climb = (isSource) => {
    const reach = new Uint8Array(h * w);
    const stack = [];
    for (let r = 0; r < h; r++) {
      for (let c = 0; c < w; c++) {
        if (isSource(r, c)) { reach[r * w + c] = 1; stack.push(r * w + c); }
      }
    }
    while (stack.length > 0) {
      const cell = stack.pop();
      const r = Math.floor(cell / w), c = cell % w;
      const here = heights[r][c];
      const next = [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]];
      for (const [nr, nc] of next) {
        if (nr < 0 || nr >= h || nc < 0 || nc >= w) continue;
        const id = nr * w + nc;
        if (!reach[id] && heights[nr][nc] >= here) { reach[id] = 1; stack.push(id); }
      }
    }
    return reach;
  };
  const pac = climb((r, c) => r === 0 || c === 0);
  const atl = climb((r, c) => r === h - 1 || c === w - 1);
  const out = [];
  for (let i = 0; i < h * w; i++) {
    if (pac[i] && atl[i]) out.push([Math.floor(i / w), i % w]);
  }
  return out;
}
JavaScript: the same two climbs with flat typed arrays and an explicit stack (order of visiting does not matter here).

Breadth-first or depth-first makes no difference here, because you only care which cells are reachable, not how far away they are. That is a useful contrast with Rotting Oranges, where the BFS layers carry meaning. The corner cells appear in both source lists; marking them reachable before pushing keeps them from being queued twice.

Complexity

R × C height map
ApproachTimeExtra space
Downhill search from every cellO((R·C)²)O(R·C) per search
Downhill search with memoized answers per cellTricky: flat regions create cycles, so results cannot simply be cachedO(R·C)
Two uphill searches from the coastsO(R·C)O(R·C) for two reach grids and the queue
R × C height map. Scroll sideways on a small screen.

The middle row is worth a sentence in an interview. Caching "can this cell reach the Pacific" while searching downhill looks attractive, but two equal neighbors can each depend on the other, and a naive memo returns an unfinished answer. The reverse search avoids the whole issue, which is part of why it is the expected solution.

Edge cases

  • Empty map: return an empty list.
  • A single row or a single column: every cell touches both oceans, so every cell is in the answer.
  • A completely flat map: water can go anywhere, so every cell qualifies.
  • A single high peak in the middle surrounded by lower land: the peak qualifies if both coasts can be reached downhill from it.
  • Plateaus, where using > instead of >= drops valid cells.

Frequent mistakes

  • Climbing with the wrong comparison, such as moving to lower neighbors in the reverse search.
  • Using strict > and missing cells connected through equal heights.
  • Assigning the edges to the wrong oceans; the Pacific is top and left in the usual statement, but read it again.
  • Sharing one visited grid between the two searches, so the second ocean's search stops early.
  • Trying to memoize the downhill search and returning wrong answers on plateaus.

Explaining the reversal

Fictional example

From brute force to two searches
Candidate
The direct approach is to follow water downhill from every cell. That is a full search per cell, so quadratic in the grid size. I will look for something better.
Candidate
Every cell on the top or left edge already drains to the Pacific. If I walk backward from those cells, only stepping to neighbors that are at least as high, I find every cell that can drain there.
Candidate
I do the same from the bottom and right edges for the Atlantic, with a separate visited grid, and return the cells both searches reached. Each search touches every cell at most once.
Interviewer
What about flat areas?
Candidate
Water can cross equal heights, so the climb uses greater-than-or-equal. That also covers a completely flat map, where every cell qualifies.

Starting a search from the edge of the grid is also the trick behind Surrounded Regions. Max Area of Island shows the forward flood fill this problem reverses, and Clone Graph applies a traversal to a graph given by references.

Practicing it with Natively

This problem rewards a single insight, and the best practice is saying that insight clearly before you code. Natively can read a height map problem from a screenshot during practice on a Mac or Windows computer, suggest the two-coast search with the >= comparison, and transcribe your answer so you can check how quickly you got from brute force to the reversal. Learn more about Natively as an interview assistant.

Questions people ask

How do you solve Pacific Atlantic Water Flow?

Run two searches in reverse. Start one from every cell on the Pacific edges and one from every cell on the Atlantic edges, each moving only to neighbors of equal or greater height. Return the cells that both searches reach.

Why search from the oceans instead of from each cell?

Following water downhill from every cell repeats work and costs O((rows × cols)²). Searching uphill from the coasts answers the question for all cells at once with two linear searches.

What is the time complexity?

O(rows × cols). Each search marks every cell at most once, and the final intersection is one more pass. Space is O(rows × cols) for the two reach grids.

Should the comparison be >= or >?

Use >=. Water flows to neighbors of equal or lower height, so in the reverse direction you may climb to equal or higher cells. Strict > misses cells joined through flat ground.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP