A rectangular island is split into cells, and heights[r][c] is the height of the cell in row r, column c. The Pacific Ocean runs along the top and left edges of the island; the Atlantic runs along the bottom and right edges.
Rain on a cell runs to a neighbour above, below, left or right when that neighbour is no higher. From any cell on an edge, it runs straight into that edge's ocean.
Return the coordinates [r, c] of every cell whose rain can reach both oceans, in any order.
Example 1
Input: heights = [[1, 2, 2],
[4, 6, 3],
[2, 1, 1]]
Output: [[0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0]]
Why: (0, 0) is a dip that only meets the Pacific;
(2, 1) and (2, 2) only meet the Atlantic2 more examples and the constraints
Example 2
Input: heights = [[42]] Output: [[0, 0]] Why: the one cell touches every edge
Example 3
Input: heights = [[1, 3],
[2, 4]]
Output: [[0, 1], [1, 0], [1, 1]]
Why: rain on the 1 cannot climb to the right or bottom edgeConstraints
- 1 ≤ rows, columns ≤ 200
- 0 ≤ each height ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Follow the rain from every cellO((m·n)²)
- Climb up from each oceanO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 200 × 200 grid | Verdict |
|---|---|---|---|
| Follow the rain from every cell | O((m·n)²) | Mention it, then move on | |
| Climb up from each ocean | O(m·n) | Best; two searches in total |
m = rows, n = columns.
Edge cases to test
- One cell. [[42]] touches all four edges, so it reaches both oceans.
- One row or one column. Every cell touches both a Pacific edge and an Atlantic edge.
- Flat ground. Equal heights let water run sideways, so every cell qualifies; the test must be ≥, not >.
- A pit. A low cell boxed in by higher ones reaches no ocean at all.
Common mistakes
- Climbing from the ocean with "neighbour ≤ current", which runs the water downhill twice.
- Using > instead of ≥, so water stops on level ground.
- Forgetting the corner cells belong to two edges, or seeding the Atlantic from the top row.
How to talk through it
- 1Clarify. Does water flow onto equal heights? Which edges belong to which ocean? Any order for the output?
- 2Give the brute force. A downhill search from every cell: O((m·n)²), and say what it repeats.
- 3Reverse the flow. Search from the oceans uphill instead: two searches cover every cell.
- 4Code one helper. A BFS that takes its start cells and returns the marked grid; call it twice.
- 5Test out loud. Run one cell, flat ground and a pit before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?