Pacific Atlantic Water Flow
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
An m x n island is described by heights, where heights[r][c] is the height of cell (r, c). Return the coordinates [r, c] of every cell from which rain can flow to both the Pacific and the Atlantic Ocean, in any order.
Understand the problem
- The Pacific Ocean touches the island's top and left edges. The Atlantic Ocean touches its bottom and right edges.
- Rain flows from a cell to a neighbor (up, down, left or right) when the neighbor is not higher: its height is less than or equal to the current one. Water can flow across flat ground, but never uphill.
- A cell on an edge drains straight into the ocean beside it.
- A cell counts if some path leads to the Pacific and some (possibly different) path leads to the Atlantic.
Pacific (top)
┌───────────────┐
│ 1 2 2 3 5 │
Pacific │ 3 2 3 4 4 │ Atlantic
(left) │ 2 4 5 3 1 │ (right)
│ 6 7 1 4 5 │
│ 5 1 1 2 4 │
└───────────────┘
Atlantic (bottom)Example 1
Input: heights = the grid above
Output: [[0,4], [1,3], [1,4], [2,2], [3,0], [3,1], [4,0]]Take the cell (2, 2), height 5. Toward the Pacific: 5 → 3 (up) → 2 (up), then off the top edge. Toward the Atlantic: 5 → 3 (right) → 1 (right), then off the right edge. Both oceans: it's in the answer.
The top-left cell (0, 0), height 1, touches the Pacific, but both its neighbors (2 and 3) are higher, so its rain can't go anywhere else. It never reaches the Atlantic.
Example 2
Input: heights = [[1]]
Output: [[0, 0]]A single cell touches all four edges, so both oceans.
Constraints
1 <= m, n <= 2000 <= heights[r][c] <= 10^5
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Instead of following water down from every cell, start at each ocean's edge and walk uphill to find every cell that can drain there; the answer is the cells both oceans reach.
The naive approach (and why it's slow)
For every cell, run a search following the water downhill and check whether it reaches both oceans. Each search can visit the whole grid, and there are m · n cells: O((m · n)²). For a 200×200 grid, that's over a billion steps, mostly repeating the same searches.
The key insight: reverse the flow
Water flows from a to a neighbor b when b is not higher than a. Turn that around:
If you're standing at
b, you can "climb back" toawhenais at least as high asb.
So start from the ocean and climb uphill (or across flat ground). Every cell you can climb to is a cell whose water can flow down to that ocean.
- Start from every Pacific edge cell at once (the top row and the left column). Search outward, only stepping to neighbors at least as high as the current cell. Mark everything reached as "can reach the Pacific".
- Do the same from every Atlantic edge cell (the bottom row and the right column).
- The answer is every cell marked by both searches.
Each search visits every cell at most once, so the whole thing is linear.
Step by step
Following one climb from the Atlantic side, starting at the right edge cell (2, 4), height 1:
| From | Height | Neighbor | Its height | Climb? (>=) |
|---|---|---|---|---|
(2, 4) | 1 | (2, 3) left | 3 | yes |
(2, 3) | 3 | (2, 2) left | 5 | yes |
(2, 2) | 5 | (2, 1) left | 4 | no, it's lower |
So (2, 2) can reach the Atlantic. The Pacific climb reaches it too (from the top edge: 2 → 3 → 5), so (2, 2) is in the answer.
The code
The reference solution is below, with comments on every important line. It runs one climb function twice, once per ocean.
How fast is it?
- Time: O(m · n). Each search visits each cell at most once.
- Memory: O(m · n) for the two "reached" grids and the stack.
Common mistakes
- Climbing with
>instead of>=. Water flows across equal heights, so equal neighbors must be included. - Starting the search from just one corner. Every cell along the ocean's two edges is a starting point.
- Mixing up which edges belong to which ocean. Pacific: top and left. Atlantic: bottom and right.
Going deeper
"Search backward from the targets" is a powerful trick whenever many sources share a few destinations. Instead of one search per source, you do one search per destination (here, two in total). You'll see it again when finding the distance from every cell to its nearest exit or gate.
Reference solution
/**
* @param {number[][]} heights
* @return {number[][]}
*/
export default function pacificAtlantic(heights) {
const rows = heights.length
const cols = heights[0].length
// Search UPHILL from the given ocean-edge cells. Returns a grid of every cell reached:
// the cells whose rain can flow down to that ocean.
function climb(starts) {
const reached = Array.from({ length: rows }, () => new Array(cols).fill(false))
const stack = []
// Every edge cell of the ocean is a starting point.
for (const [r, c] of starts) {
if (!reached[r][c]) {
reached[r][c] = true
stack.push([r, c])
}
}
while (stack.length > 0) {
const [r, c] = stack.pop()
for (const [nr, nc] of [
[r + 1, c],
[r - 1, c],
[r, c + 1],
[r, c - 1],
]) {
if (
nr >= 0 &&
nr < rows &&
nc >= 0 &&
nc < cols &&
!reached[nr][nc] && // not visited yet
heights[nr][nc] >= heights[r][c] // at least as high: water could flow from it to here
) {
reached[nr][nc] = true
stack.push([nr, nc])
}
}
}
return reached
}
const pacificStarts = []
const atlanticStarts = []
// Pacific: left column and top row. Atlantic: right column and bottom row.
for (let r = 0; r < rows; r++) {
pacificStarts.push([r, 0])
atlanticStarts.push([r, cols - 1])
}
for (let c = 0; c < cols; c++) {
pacificStarts.push([0, c])
atlanticStarts.push([rows - 1, c])
}
const pacific = climb(pacificStarts)
const atlantic = climb(atlanticStarts)
const result = []
// The answer: cells reached from BOTH oceans.
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) if (pacific[r][c] && atlantic[r][c]) result.push([r, c])
}
return result
}export default function pacificAtlantic(heights: number[][]): number[][] {
const rows = heights.length
const cols = heights[0].length
// Search UPHILL from the given ocean-edge cells. Returns a grid of every cell reached:
// the cells whose rain can flow down to that ocean.
function climb(starts: Array<[number, number]>): boolean[][] {
const reached = Array.from({ length: rows }, () => new Array<boolean>(cols).fill(false))
const stack: Array<[number, number]> = []
// Every edge cell of the ocean is a starting point.
for (const [r, c] of starts) {
if (!reached[r][c]) {
reached[r][c] = true
stack.push([r, c])
}
}
while (stack.length > 0) {
const [r, c] = stack.pop()!
for (const [nr, nc] of [
[r + 1, c],
[r - 1, c],
[r, c + 1],
[r, c - 1],
]) {
if (
nr >= 0 &&
nr < rows &&
nc >= 0 &&
nc < cols &&
!reached[nr][nc] && // not visited yet
heights[nr][nc] >= heights[r][c] // at least as high: water could flow from it to here
) {
reached[nr][nc] = true
stack.push([nr, nc])
}
}
}
return reached
}
const pacificStarts: Array<[number, number]> = []
const atlanticStarts: Array<[number, number]> = []
// Pacific: left column and top row. Atlantic: right column and bottom row.
for (let r = 0; r < rows; r++) {
pacificStarts.push([r, 0])
atlanticStarts.push([r, cols - 1])
}
for (let c = 0; c < cols; c++) {
pacificStarts.push([0, c])
atlanticStarts.push([rows - 1, c])
}
const pacific = climb(pacificStarts)
const atlantic = climb(atlanticStarts)
const result: number[][] = []
// The answer: cells reached from BOTH oceans.
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) if (pacific[r][c] && atlantic[r][c]) result.push([r, c])
}
return result
}def pacific_atlantic(heights: list[list[int]]) -> list[list[int]]:
rows, cols = len(heights), len(heights[0])
# Search UPHILL from the given ocean-edge cells. Returns every cell reached:
# the cells whose rain can flow down to that ocean.
def climb(starts: list[tuple[int, int]]) -> set[tuple[int, int]]:
reached = set(starts) # every edge cell of the ocean is a starting point
stack = list(reached)
while stack:
r, c = stack.pop()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if (
0 <= nr < rows
and 0 <= nc < cols
and (nr, nc) not in reached # not visited yet
# at least as high: water could flow from it to here
and heights[nr][nc] >= heights[r][c]
):
reached.add((nr, nc))
stack.append((nr, nc))
return reached
# Pacific: left column and top row. Atlantic: right column and bottom row.
pacific = climb([(r, 0) for r in range(rows)] + [(0, c) for c in range(cols)])
atlantic = climb([(r, cols - 1) for r in range(rows)] + [(rows - 1, c) for c in range(cols)])
# The answer: cells reached from BOTH oceans (& is set intersection).
return [[r, c] for r, c in sorted(pacific & atlantic)]