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?- A. 3 1
- B. 2 2
- C. 2 1
- 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
- Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open…
- Problem: Count paths modulo 10⁹ + 7 from the top-left to the bottom-right of a 3 × 3 board whose centre is blocked, moving right, down or…
- Problem: Find the maximum number of points you can collect in a grid going right/down from top-left to bottom-right and then reconstruct…
- Problem: n ≤ 10⁵ tasks with durations and deadlines; complete as many tasks as possible, one at a time, each finishing by its deadline…
- Problem: Find the median of two sorted arrays of sizes m and n (up to 10⁶ each) in better than linear time. What is the optimal complexity?
- Problem: A social graph has V = 10⁶ users and E = 10⁷ friendships. You must store it to run BFS. Which representation is appropriate and…