Pacific Atlantic Water Flow
Problem Statement
You are given a grid of heights for an island. The Pacific Ocean touches the top and left edges, and the Atlantic Ocean touches the bottom and right edges. Water flows from a cell to a neighbour (up, down, left or right) when that neighbour is the same height or lower. Water can also flow from any edge cell into the ocean that touches it. Return every cell from which water can reach both oceans.
heights, an m × n grid of integers. heights[r][c] is the height of the cell at row r, column c.
A list of [row, col] pairs, one for each cell that can reach both oceans. The pairs may come in any order.
Each listed cell reaches both oceans. For example, (1,3) flows up to (0,3), which touches the Pacific, and right to (1,4), which touches the Atlantic.
The single cell touches both oceans.
- • 1 ≤ m, n ≤ 200, where m is the number of rows and n is the number of columns
- • 0 ≤ heights[r][c] ≤ 10^5
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each cell, run a fresh downhill search; keep the cell if the search reaches both oceans
Walk uphill from the Pacific edge and from the Atlantic edge; the answer is the cells both reach
For each cell, run a search that moves to neighbours that are the same height or lower. If the search reaches a top or left edge cell and a bottom or right edge cell, the start reaches both oceans. Every cell runs its own search, so the same downhill paths are walked again and again.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.