Path With Minimum Effort (LeetCode 1631): Solution and Explanation

Medium
Array
Binary Search
Depth First Search
Breadth First Search
Union Find
Heap
Matrix

You are given a grid of heights and must walk from the top-left cell to the bottom-right cell, moving in four directions. A path's effort is the largest absolute height difference between any two consecutive cells on it. Return the smallest effort any path can achieve.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The cost of a path is not a sum, it is a maximum, so a plain BFS that counts steps does not help, and trying every path is exponential. But notice that the effort can only stay the same or grow as a path gets longer: extending a path to a new cell gives effort max(old effort, new step). That monotonic property is exactly what Dijkstra's algorithm needs.

So run Dijkstra with a modified relaxation. Keep dist[r][c], the smallest effort found so far to reach a cell, and a min-heap ordered by effort. When a cell is popped, its effort is final because any other route to it would have to pass through cells with effort at least as large. Moving to a neighbor costs max(effort, abs(height difference)), and if that beats the neighbor's recorded value, push it.

Since the heap always pops the smallest effort first, the first time the target cell comes off the heap its effort is the answer. Stale heap entries, those whose effort is larger than the cell's current best, are skipped when popped.

Approach: Dijkstra with max-edge path cost

  1. Fill dist with infinity, set dist[0][0] = 0, and push (0, 0, 0) onto a min-heap of (effort, row, col).
  2. Pop the smallest-effort entry. If it is the bottom-right cell, return its effort.
  3. If the popped effort is larger than dist[r][c], the entry is stale, so skip it.
  4. For each in-bounds neighbor, compute new_effort = max(effort, abs(heights[nr][nc] - heights[r][c])).
  5. If new_effort is smaller than dist[nr][nc], update it and push the neighbor.
  6. If the heap somehow empties, return dist[m-1][n-1].

Step-by-step example

heights = [[1,2,2],[3,8,2],[5,3,5]]
  1. Start at (0,0) with effort 0. Neighbors (0,1) costs 1 and (1,0) costs 2; both are pushed.
  2. Pop (0,1) at 1. Neighbor (0,2) gets max(1, 0) = 1 and (1,1) gets max(1, 6) = 6. Pop (0,2) at 1, which gives (1,2) effort 1. Pop (1,2) at 1, which gives (2,2) effort max(1, 3) = 3.
  3. Pop (1,0) at 2. It improves (1,1) to max(2, 5) = 5 and gives (2,0) effort 2.
  4. Pop (2,0) at 2, giving (2,1) effort max(2, 2) = 2. Pop (2,1) at 2, which improves (2,2) from 3 to max(2, 2) = 2.
  5. Pop (2,2) at effort 2. It is the target, so the answer is 2, via the path 1, 3, 5, 3, 5.

Code: Python, Java, C++

1class Solution:
2    def minimumEffortPath(self, heights: List[List[int]]) -> int:
3        m, n = len(heights), len(heights[0])
4        dist = [[float('inf')] * n for _ in range(m)]
5        dist[0][0] = 0
6        heap = [(0, 0, 0)]  # (effort, row, col)
7        dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
8
9        while heap:
10            effort, r, c = heapq.heappop(heap)
11            if r == m - 1 and c == n - 1:
12                return effort
13            if effort > dist[r][c]:
14                continue
15            for dr, dc in dirs:
16                nr, nc = r + dr, c + dc
17                if 0 <= nr < m and 0 <= nc < n:
18                    new_effort = max(effort, abs(heights[nr][nc] - heights[r][c]))
19                    if new_effort < dist[nr][nc]:
20                        dist[nr][nc] = new_effort
21                        heapq.heappush(heap, (new_effort, nr, nc))
22
23        return dist[m - 1][n - 1]

Time and space complexity

Time

O(m × n × log(m × n))

Each cell can be pushed a few times (once per improvement from one of its four neighbors), and every heap operation costs O(log(m × n)).

Space

O(m × n)

The dist grid holds one value per cell and the heap holds at most a constant multiple of the cell count.

Other approaches

Binary search plus BFS (time O(m × n × log H), space O(m × n))

Binary search the answer between 0 and the largest height difference, and for each guess run a BFS that only uses steps no larger than the guess. Simple and effective when heights are bounded.

Union-find over sorted edges (time O(m × n × log(m × n)), space O(m × n))

Sort all edges between adjacent cells by height difference and union them in that order, stopping as soon as the start and end cells are connected. The weight of the last edge added is the answer.

Common mistakes

  • Summing the differences like a normal shortest path. The effort is a maximum, so the relaxation must use max(effort, diff), not effort + diff.
  • Returning when the target is first pushed rather than first popped. A later route might still lower its effort before it reaches the top of the heap.
  • Skipping the stale-entry check. Without if effort > dist[r][c]: continue, outdated entries trigger needless relaxations and slow the search down.
  • Forgetting that a 1 by 1 grid has effort 0. The code handles this because the start cell is also the target and is popped immediately.

Frequently asked questions

Why does Dijkstra work when the cost is a maximum?

Dijkstra only needs path costs that never decrease as the path grows. Taking the max with a non-negative step satisfies that, so the first time a cell is popped its effort is optimal.

What is the time complexity of Path With Minimum Effort?

With Dijkstra and a binary heap it is O(m × n × log(m × n)), since each cell is relaxed a bounded number of times and each heap operation is logarithmic.

Can I solve it with binary search?

Yes. Binary search the effort limit and check reachability with BFS or DFS using only steps within the limit. It adds a factor of log of the height range instead of a log of the grid size.

Why not use plain BFS?

Plain BFS minimizes the number of steps, not the largest step. A longer path with gentle slopes can have lower effort than a short steep one.