You get heights, a grid with rows rows and columns columns, where heights[r][c] is the height of that cell. You start at the top-left cell and want to reach the bottom-right cell, moving one cell up, down, left or right at a time.
The effort of a route is its single hardest step: the largest height difference between two cells next to each other on the route. Return the smallest effort of any route from start to goal.
Example 1
Input: heights = [[2, 5, 3],
[4, 9, 6],
[5, 7, 8]]
Output: 2
Why: 2 → 4 → 5 → 7 → 8 has steps 2, 1, 2, 12 more examples and the constraints
Example 2
Input: heights = [[4, 4, 4, 4]] Output: 0 Why: the ground is flat all the way
Example 3
Input: heights = [[1, 10], [3, 6]] Output: 3 Why: 1 → 3 → 6 beats 1 → 10 → 6, whose first step is 9
Constraints
- 1 ≤ rows, columns ≤ 100
- 1 ≤ heights[r][c] ≤ 1,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Binary search on the effortO(m·n·log H)
- Dijkstra with a min-heapO(m·n·log(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 100 × 100 grid | Verdict |
|---|---|---|---|
| Binary search on the effort | O(m·n·log H) | Passes; about 20 flood fills | |
| Dijkstra with a min-heap | O(m·n·log(m·n)) | Best; one sweep, stops at the goal |
m × n = size of the grid, H = range of heights (up to 1,000,000).
Edge cases to test
- One cell. [[7]] needs no step, so the effort is 0.
- Flat ground. All heights equal gives 0.
- One row or column. There is only one route; the answer is its largest step.
- Detour wins. A longer route with gentle steps can beat a short steep one, as in Example 3.
Common mistakes
- Adding up the height changes, as in a normal shortest path, instead of taking the largest.
- Only moving right and down; the best route may need to go up or left.
- Returning when the goal is pushed instead of when it is popped, before a better route can lower its effort.
How to talk through it
- 1Clarify. Four directions only? Is the effort the largest step, not the total? Can the grid be one cell?
- 2Reframe. Cells are nodes, steps are edges weighted by height change, and a route costs its largest edge.
- 3Give the binary search. For a fixed limit, a flood fill says yes or no, and yes stays yes as the limit grows.
- 4Code Dijkstra. Min-heap on effort, new effort is max(e, step), skip stale entries, stop at the goal.
- 5Test out loud. Run one cell, flat ground and a grid where the detour wins.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?