Path With Minimum Effort

Medium

Topics
ArrayBinary SearchUnion FindHeapMatrixShortest Path

You are given a grid heights of size rows x columns. You start at the top-left cell and want to reach the bottom-right cell, moving up, down, left, or right.

The effort of a route is the maximum absolute height difference between two consecutive cells along it.

Return the minimum effort required to travel from the top-left to the bottom-right cell.

Example 1

012213822535012
A route’s effort is its single biggest step between adjacent heights, not the total climb. The shaded route keeps that maximum down to 2, the answer.
2D grid — one row per line.
Input:  heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route 1 -> 2 -> 2 -> 2 -> 5 has a maximum difference of 2, better than going through 8.

Example 2

012313842535012
Input:  heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1

Constraints

  • rows == heights.length
  • columns == heights[i].length
  • 1 <= rows, columns <= 100
  • 1 <= heights[i][j] <= 10^6
Editorial — intuition, approach, complexity and pitfalls

Intuition

The cost of a path is a maximum over its edges, not a sum, so plain Dijkstra's relaxation does not apply unchanged — but it almost does. Replace "distance so far plus edge weight" with "max(distance so far, edge weight)" and the greedy argument still holds, because that combining function is monotone. Pop the cell with the smallest bottleneck first and you have a minimax shortest path.

Approach

  1. Keep a grid effort of best-known bottleneck values, all infinity except the start at 0.
  2. Use a min-heap keyed by bottleneck value. Pop the smallest, and if it is the destination you are done — the first time you pop it, its value is optimal.
  3. For each neighbour, the candidate cost is max(effort[cur], abs(height[next] - height[cur])). Push and record it if that beats the stored value.
  4. Two alternatives interview well: binary search the answer and BFS to test feasibility at each threshold, or sort all edges ascending and union cells until the corners connect (Kruskal).
import heapq

class Solution:
    def minimumEffortPath(self, heights):
        m, n = len(heights), len(heights[0])
        effort = [[float("inf")] * n for _ in range(m)]
        effort[0][0] = 0
        pq = [(0, 0, 0)]
        while pq:
            cost, r, c = heapq.heappop(pq)
            if r == m - 1 and c == n - 1:
                return cost
            if cost > effort[r][c]:
                continue
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < m and 0 <= nc < n:
                    nxt = max(cost, abs(heights[nr][nc] - heights[r][c]))
                    if nxt < effort[nr][nc]:
                        effort[nr][nc] = nxt
                        heapq.heappush(pq, (nxt, nr, nc))
        return 0

Dry Run

grid  1 2 2
      3 8 2
      5 3 5
The cost of a path is the LARGEST single step on it, so the relaxation combines
with max rather than plus. Dijkstra still works, because a max is monotone.
  pop (0, 0,0)   improves (1,0) to 2 and (0,1) to 1
  pop (1, 0,1)   improves (1,1) to 6 and (0,2) to 1
  pop (1, 0,2)   improves (1,2) to 1
  pop (1, 1,2)   improves (2,2) to 3
  pop (2, 1,0)   improves (2,0) to 2 and (1,1) 6->5
  pop (2, 2,0)   improves (2,1) to 2
  pop (2, 2,1)   improves (2,2) 3->2
  pop (2, 2,2)   this is the destination
answer 2
Note (2,2) is improved twice, from 3 down to 2, by a route arriving from the left
rather than from above. Movement is four-directional and may go UP or LEFT, so
this is not a DP over a monotone grid and a row-major single pass would miss that
second route entirely.
The pop at (1,1) is worth following too. It is first set to 6 via (0,1) and later
to 5 via (1,0); the stale (6, 1, 1) entry stays on the heap and is discarded by
`if cost > effort[r][c]: continue` when it surfaces. Without that guard nothing is
wrong with the answer, but the heap keeps growing and large grids slow sharply.
Adding the differences instead of maxing them solves a different problem: this
grid then returns 4. And a 1x1 grid needs no moves at all, which the early
destination return handles by giving 0 before any neighbour is examined.

Complexity

  • Time — O(m x n log(m x n)) — Dijkstra over a grid graph with 4 edges per cell.
  • Space — O(m x n) for the effort grid and the heap.

Common Pitfalls

  • Adding edge weights instead of taking their maximum solves a different problem entirely. The combining step is max.
  • A 1x1 grid needs no moves, so the answer is 0. Make sure the start-equals-destination case returns before entering the loop body.
  • Skip stale heap entries with the cost > effort[r][c] guard, or the heap grows and the run slows sharply on large grids.
  • Movement is four-directional and may go up or left — this is not a DP over a monotone grid, so a row-major single pass gives wrong answers.

Full Solution — all languages

class Solution:
    def minimumEffortPath(self, grid):
        import heapq
        rows, cols = len(grid), len(grid[0])
        effort = [[float('inf')] * cols for _ in range(rows)]
        effort[0][0] = 0
        heap = [(0, 0, 0)]
        while heap:
            cost, r, c = heapq.heappop(heap)
            if r == rows - 1 and c == cols - 1:
                return cost
            if cost > effort[r][c]:
                continue
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols:
                    step = max(cost, abs(grid[nr][nc] - grid[r][c]))
                    if step < effort[nr][nc]:
                        effort[nr][nc] = step
                        heapq.heappush(heap, (step, nr, nc))
        return 0
SensAI
Beta
Tap the mic to stop voice mode