mediumGraphsFacebookGoogle
Watershed Divide
A hydrology grid identifies cells whose rainwater can flow to BOTH the Pacific (top/left borders) and Atlantic (bottom/right borders) along downhill-only paths.
Given an m×n matrix of heights, return all coordinates whose water can flow to both the top/left and bottom/right ocean borders.
Choose approach
1P
2P
2P
3P
5★
3P
2P
3P
4★
4★
2P
4P
5★
3A
1A
6★
7★
1A
4A
5A
5★
1A
1A
2A
4A
1/1
Narrationstep 1 of 1
Reverse flow from Pacific borders (P) and Atlantic borders (A). ★ = reaches both.
Variables
dualReach=7
How to think about it
- Downhill-forward from each cell is quadratic; reverse-uphill from borders is linear.
- Each cell is visited at most twice (once per ocean).
- Answer = Pacific ∩ Atlantic.
Edge cases to catch in interview
- Corner cell -> reaches both automatically.
- Flat heights -> every cell reaches both.
Examples
Example 1
[[0,0],[0,1],[1,0],[1,1]]{"grid":[[1,1],[1,1]]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed