Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the minimum effort path in a grid where effort is the maximum absolute height difference between consecutive cells.

Problem: Find the minimum effort path in a grid where effort is the maximum absolute height difference between consecutive cells.
import heapq
def effort(h):
    R, C = len(h), len(h[0]); best = [[float('inf')] * C for _ in range(R)]
    best[0][0] = 0; pq = [(0, 0, 0)]
    while pq:
        e, r, c = heapq.heappop(pq)
        if (r, c) == (R - 1, C - 1): return e
        if e > best[r][c]: continue
        for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= nr < R and 0 <= nc < C:
                ne = max(e, abs(h[nr][nc] - h[r][c]))
                if ne < best[nr][nc]: best[nr][nc] = ne; heapq.heappush(pq, (ne, nr, nc))
print(effort([[1, 2, 2], [3, 8, 2], [5, 3, 5]]), effort([[1, 2, 3], [3, 8, 4], [5, 3, 5]]))
What is printed?
  1. A. 3 1
  2. B. 2 2
  3. C. 2 1
  4. D. 1 1

Correct answer: C. 2 1

Dijkstra where a path's cost is its largest step (minimax). First grid: 1 → 3 → 5 → 3 → 5 has steps 2, 2, 2, 2 → 2. Second: 1 → 2 → 3 → 4 → 5 has every step 1. Summing differences instead of taking the max would choose different paths. O(RC log RC).

More Coding Interview Problems questions

Exams that ask this topic