FAANGPrep Sprint
Pacific Atlantic Water Flow
Find cells that can flow to both oceans.
Examples
Cells that can reach both Pacific (Top/Left) and Atlantic (Bottom/Right).
Problem Understanding
Water flows downhill (neighbor height <= current height).
- Pacific Ocean: Touches Left and Top edges.
- Atlantic Ocean: Touches Right and Bottom edges.
Find all coordinates (r, c) from which water can flow to BOTH oceans.
Algorithm Strategy (Backwards Flow)
Simulating flow from every cell is slow (O(MN * MN)).
Better Idea: Reverse the flow! Start from the Oceans and go uphill.
- Pacific Set: Run DFS from all Top/Left edges. Store reachable cells.
- Atlantic Set: Run DFS from all Bottom/Right edges. Store reachable cells.
- Result: The intersection of both sets.
Visualization
NUMBERS = HEIGHTS · PACIFIC: TOP + LEFT · ATLANTIC: BOTTOM + RIGHT · GREEN = BOTH
PACIFIC — TOP ROW
Pacific
0
Atlantic
0
Both
0
call stack · Pacific
No dfs running
Top row (0, 0) touches the Pacific: call dfs(0, 0) with prev = its own height, 1
Next
dfs(0, 0): height 1 ≥ 1 — it drains to the Pacific. Mark it
heights
Both oceans climb in from their edges: the Pacific from the top row and left column, the Atlantic from the bottom row and right column, in the order the code calls them. A call returns if it leaves the grid, reaches a cell this ocean already reached, or would have to go downhill. Each ocean keeps its own colour; cells both oceans reach turn green, and the last pass collects them in row order.
