Path With Minimum Effort solution explained

Path With Minimum Effort asks for a route through a grid of heights from the top-left cell to the bottom-right, moving up, down, left or right, where a route's effort is the largest height difference between any two consecutive cells on it; return the smallest effort possible. Run Dijkstra's algorithm but combine steps with max instead of adding them, or binary search the allowed step and test reachability with a breadth-first search. Dijkstra runs in O(R·C log(R·C)).

By Published 10 min read

The problem, restated

You are given a grid of positive heights. Starting from the top-left cell, you want to reach the bottom-right cell, moving one cell at a time up, down, left or right. Each move costs the absolute difference between the two heights, and the effort of a whole route is its most expensive single move. Return the lowest effort any route can have.

3 8 4
5 9 6
6 7 9
Our own 3 by 3 example.

Going straight along the top row starts with a climb from 3 to 8, an effort of at least 5. Going down the left side and along the bottom, 3 to 5 to 6 to 7 to 9, has steps of 2, 1, 1 and 2, so its effort is 2. No route can do better, because both cells next to the start differ from 3 by at least 2. The answer is 2.

What the interviewer is checking

The question is whether you recognize a shortest-path problem with an unusual cost. Candidates who reach for plain breadth-first search count cells, which is wrong. Candidates who try dynamic programming moving only right and down miss routes that double back. The interviewer hopes to hear that this is a graph with weighted edges, that the route cost is a maximum, and why Dijkstra's greedy choice is still safe. Offering the binary-search version as a second idea is a strong signal.

Brute force: try every route

A depth-first search can walk every simple route from the start to the end, tracking the worst step so far and pruning any route whose worst step already matches the best found. It is correct but the number of routes grows exponentially with the grid size, so it only works as a reference on tiny grids.

def min_effort_brute(heights):
    rows, cols = len(heights), len(heights[0])
    best = float("inf")
    on_path = [[False] * cols for _ in range(rows)]
    def walk(r, c, worst):
        nonlocal best
        if worst >= best:
            return  # cannot improve on a route already found
        if (r, c) == (rows - 1, cols - 1):
            best = worst
            return
        on_path[r][c] = True
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and not on_path[nr][nc]:
                walk(nr, nc, max(worst, abs(heights[nr][nc] - heights[r][c])))
        on_path[r][c] = False
    walk(0, 0, 0)
    return best
Python: exhaustive search over simple routes, for testing only.

Idea 1: binary search on the allowed step

Flip the question around: for a given limit, can you get from corner to corner using only steps of at most that size? That is a plain reachability check with breadth-first search. The answer is monotone, since a larger limit never blocks a route a smaller one allowed, so binary search the smallest limit that works between 0 and the gap between the highest and lowest cell.

from collections import deque

def min_effort_binary_search(heights):
    rows, cols = len(heights), len(heights[0])

    def reachable(limit):
        seen = [[False] * cols for _ in range(rows)]
        seen[0][0] = True
        queue = deque([(0, 0)])
        while queue:
            r, c = queue.popleft()
            if (r, c) == (rows - 1, cols - 1):
                return True
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if (0 <= nr < rows and 0 <= nc < cols and not seen[nr][nc]
                        and abs(heights[nr][nc] - heights[r][c]) <= limit):
                    seen[nr][nc] = True
                    queue.append((nr, nc))
        return False

    low, high = 0, max(map(max, heights)) - min(map(min, heights))
    while low < high:  # smallest limit that still connects the corners
        mid = (low + high) // 2
        if reachable(mid):
            high = mid
        else:
            low = mid + 1
    return low
Python: binary search over the limit, breadth-first search to test it.

Idea 2: Dijkstra with max instead of plus

Keep, for every cell, the smallest worst-step found so far to reach it, and process cells from a min-heap in order of that value. When you leave a cell with value w along a step of size d, the neighbor's candidate is max(w, d). The greedy rule still holds because extending a route can never lower its worst step, exactly as adding a non-negative edge can never shorten a path. So the first time the target comes off the heap, its value is final.

import heapq

def min_effort(heights):
    rows, cols = len(heights), len(heights[0])
    effort = [[float("inf")] * cols for _ in range(rows)]
    effort[0][0] = 0
    heap = [(0, 0, 0)]  # (worst step so far, row, col)
    while heap:
        worst, r, c = heapq.heappop(heap)
        if (r, c) == (rows - 1, cols - 1):
            return worst
        if worst > effort[r][c]:
            continue  # stale entry
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols:
                candidate = max(worst, abs(heights[nr][nc] - heights[r][c]))
                if candidate < effort[nr][nc]:
                    effort[nr][nc] = candidate
                    heapq.heappush(heap, (candidate, nr, nc))
    return 0
Python: minimax Dijkstra with heapq.
// A small binary min-heap of [key, row, col] arrays, ordered by key.
class MinHeap {
  constructor() { this.items = []; }
  get size() { return this.items.length; }
  push(item) {
    const a = this.items;
    a.push(item);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (a[p][0] <= a[i][0]) break;
      [a[p], a[i]] = [a[i], a[p]];
      i = p;
    }
  }
  pop() {
    const a = this.items;
    const top = a[0];
    const last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1, r = l + 1;
        let m = i;
        if (l < a.length && a[l][0] < a[m][0]) m = l;
        if (r < a.length && a[r][0] < a[m][0]) m = r;
        if (m === i) break;
        [a[m], a[i]] = [a[i], a[m]];
        i = m;
      }
    }
    return top;
  }
}

function minimumEffortPath(heights) {
  const rows = heights.length;
  const cols = heights[0].length;
  const effort = heights.map((row) => row.map(() => Infinity));
  effort[0][0] = 0;
  const heap = new MinHeap();
  heap.push([0, 0, 0]);
  const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  while (heap.size > 0) {
    const [worst, r, c] = heap.pop();
    if (r === rows - 1 && c === cols - 1) return worst;
    if (worst > effort[r][c]) continue; // an older, worse entry
    for (const [dr, dc] of moves) {
      const nr = r + dr, nc = c + dc;
      if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
      const candidate = Math.max(worst, Math.abs(heights[nr][nc] - heights[r][c]));
      if (candidate < effort[nr][nc]) {
        effort[nr][nc] = candidate;
        heap.push([candidate, nr, nc]);
      }
    }
  }
  return 0;
}
JavaScript: the same search with a small hand-written binary heap.

How the heap behaves on the example

From the 3 in the corner, the heap receives the 5 below at effort 2 and the 8 to the right at effort 5. The 5 comes off first and offers the 6 below it at effort 2 and the 9 in the middle at effort 4. The 6 then offers the 7 at effort 2, and the 7 offers the target 9 at effort 2 (and lowers the middle 9 to 2 as well). Every cell popped before the target has effort at most 2 (the start has 0). With Python's tie order the middle 9 is popped before the target and lowers the 8 to 2, so the 8's entry at 5 goes stale and is skipped if it is ever popped.

A third route to the same answer is a union-find: sort every edge between neighbors by height difference, join cells in that order, and stop at the first edge after which the two corners share a set. That edge's difference is the answer. It is the same reasoning as building a minimum spanning tree.

Complexity

R rows, C columns, H = highest minus lowest height
ApproachTimeExtra space
Every simple routeExponentialO(R·C) for the recursion
Binary search plus breadth-first searchO(R·C · log H)O(R·C)
Minimax DijkstraO(R·C · log(R·C))O(R·C)
Sorted edges plus union-findO(R·C · log(R·C)) for the sortO(R·C)
R rows, C columns, H = highest minus lowest height. Scroll sideways on a small screen.

Edge cases

  • A single cell: start and end are the same, so the effort is 0.
  • A single row or column: there is only one route, so the answer is its largest adjacent difference.
  • All heights equal: the answer is 0.
  • Routes that go up and back down: moves in all four directions are allowed, so do not restrict to right and down.
  • Large height values: the binary search range is the height spread, not the grid size.

Mistakes to avoid

  • Summing the step sizes instead of taking their maximum.
  • Dynamic programming over right and down moves only, which misses detours.
  • Plain breadth-first search by number of moves, which finds short routes, not easy ones.
  • Stopping when the target is first pushed onto the heap instead of when it is popped.
  • Off-by-one binary search bounds that never test a limit of 0.

Follow-up questions

  • Return the route itself. Store the cell each one was reached from and walk back from the target.
  • Diagonal moves are allowed. Add four more moves; the algorithm is unchanged.
  • Effort is the sum of steps, not the largest. Then it is ordinary Dijkstra with addition.
  • Many start and end pairs. Build a minimum spanning tree once (every minimax route lies along it), or answer offline by sorting queries by limit and joining cells with union-find.

How to explain it

Fictional example

Explaining the cost model before coding
Candidate
Each cell is a node with edges to its four neighbors, weighted by the height difference. The cost of a route is its biggest edge, not the total.
Candidate
Dijkstra still works if I combine with max instead of plus, because extending a route can't make its biggest edge smaller. I pop cells in order of their best known effort and stop when the target comes off the heap.
Candidate
If you'd like a simpler check, I can also binary search the limit and run a breadth-first search for each guess.

Path with Maximum Probability is another Dijkstra with a changed combine step, multiplication instead of max. Find the City With the Smallest Number of Neighbors needs distances from every node at once. Trapping Rain Water II also walks a height grid with a min-heap, and Making A Large Island is a grid problem built on labeling instead. Browse the rest on the coding problems hub.

Practicing weighted grids with Natively

During practice on Mac or Windows, Natively can read a height grid from a screenshot and work through the first few heap pops with you, which is a quick way to see why a short route can lose. Ask it for a suggested implementation once you have explained the max-instead-of-plus idea in your own words, and use the saved transcript afterward to check that you justified why Dijkstra still applies. The AI interview assistant page has more.

Questions people ask

How do you solve Path With Minimum Effort?

Run Dijkstra's algorithm on the grid where a route's cost is its largest single height change: combine with max instead of adding, and return the effort when the bottom-right cell comes off the heap.

Why does Dijkstra work for Path With Minimum Effort?

Extending a route can never lower its worst step, just as adding a non-negative edge never shortens a path, so the first time the target is popped its effort is final.

Can you use binary search for Path With Minimum Effort?

Yes. Binary search the largest allowed step and use a breadth-first search to check whether the corners connect with steps no bigger than that.

What is the time complexity of Path With Minimum Effort?

O(R·C log(R·C)) with Dijkstra, or O(R·C log H) with binary search, where H is the spread of heights.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP