Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Move from the top-left to the bottom-right cell of a height grid (4 directions). The effort of a route is the largest absolute height difference between consecutive cells. Find the minimum effort.

Problem: Move from the top-left to the bottom-right cell of a height grid (4 directions). The effort of a route is the largest absolute height difference between consecutive cells. Find the minimum effort.
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 x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= x < R and 0 <= y < C:
                ne = max(e, abs(h[x][y] - h[r][c]))
                if ne < best[x][y]: best[x][y] = ne; heapq.heappush(pq, (ne, x, y))
print(effort([[1, 3, 8], [6, 4, 2], [7, 9, 3]]))
What is printed?
  1. A. 2
  2. B. 5
  3. C. 3
  4. D. 4

Correct answer: A. 2

Dijkstra with 'max of edges' instead of 'sum'. Route 1 → 3 → 4 → 2 → 3 has steps 2, 1, 2, 1, so its effort is 2; effort 1 is impossible because both first moves (to 3 or 6) already cost at least 2.

More Coding Interview Problems questions

Exams that ask this topic