oneby7

Advanced Graphs Weighted shortest paths

472. Path With Minimum Effort

Medium 147 DSA Sheet

You are given a grid of heights, heights. heights[i][j] is the height of the cell in row i, column j. You start in the top-left cell and want to reach the bottom-right cell. Each step moves to the cell directly above, below, left or right. A path may turn and go back the way it came as often as it likes.

The effort of a path is the largest difference in height between two cells that come one after the other on it. Return the smallest effort of any path from the top-left cell to the bottom-right cell.

Example 1

286646377186

Input: heights = [[2, 8, 6, 6], [4, 6, 3, 7], [7, 1, 8, 6]]

Output: 2

Explanation: The path 2 → 4 → 6 → 8 → 6 → 6 → 7 → 6 goes down, right, back up, along the top row and down the right side. No step on it changes the height by more than 2.

Example 2

5183

Input: heights = [[5, 1, 8, 3]]

Output: 7

Explanation: There is only one path, and its largest step is from 1 to 8.

Example 3

10⁹1110⁹

Input: heights = [[1000000000, 1], [1, 1000000000]]

Output: 999999999

Explanation: Every path passes a cell of height 1, and the step down to it is 999999999.

Check your understanding

Work out the answer for this input before you write any code.

heights = [[9, 3, 1, 3], [9, 7, 1, 9], [9, 1, 2, 5]]

Constraints

  • m == heights.length, n == heights[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • 1 ≤ heights[i][j] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.