TRT
Sign in
mediumAdvancedLeetCode#reverse search#multi-source DFS

Pacific Atlantic water flow

Find the cells whose water can reach both oceans by searching uphill from each ocean's border and intersecting the results.

The Runtime Theory Team1 min read
Taught inDepth-first searchPro — members onlyDepth-first search follows one path as far as it can, then backs up and tries the next. It is the natural way to flood a region, explore every possibility, or ask what is reachable, as long as you watch its depth.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inheights = [[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]]

out[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]

inheights = [[1]]

out[[0, 0]]

Water flows from a cell to a neighbor of equal or lower height. The Pacific touches the top and left edges and the Atlantic the bottom and right. Return every cell from which water can reach both oceans.

Before you code

Searching downhill from every cell repeats the same exploration many times. Reverse it: from each ocean, search uphill (to equal or higher neighbors). Each search marks every cell that drains into that ocean.

Hints

  1. Start one DFS or BFS from all Pacific border cells and one from all Atlantic border cells.
  2. Move to a neighbor only if its height is at least the current cell's.
  3. The answer is the cells marked by both searches. Total O(rows × columns).

Production & complexity notes

When solving Pacific Atlantic water flow on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Depth-first search to reinforce the underlying pattern.

What it practices

Reversing the direction of a search, from Depth-first search.

Not started

Sign in to save your learning progress.

Sign in to save