Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Water level t floods every cell of height ≤ t. Find the smallest t at which you can swim from the top-left to the bottom-right cell (minimise the maximum height on the path).

Problem: Water level t floods every cell of height ≤ t. Find the smallest t at which you can swim from the top-left to the bottom-right cell (minimise the maximum height on the path).
import heapq
def swim(g):
    n = len(g); h = [(g[0][0], 0, 0)]; seen = {(0, 0)}; best = 0
    while h:
        t, r, c = heapq.heappop(h); best = max(best, t)
        if (r, c) == (n - 1, n - 1): return best
        for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= x < n and 0 <= y < n and (x, y) not in seen:
                seen.add((x, y)); heapq.heappush(h, (g[x][y], x, y))
print(swim([[0, 5, 9], [2, 7, 6], [3, 8, 4]]))
What is printed?
  1. A. 8
  2. B. 4
  3. C. 9
  4. D. 7

Correct answer: D. 7

Always expanding the lowest reachable cell is a Dijkstra/Prim variant on the bottleneck: the route 0 → 5 → 7 → 6 → 4 never exceeds 7, while every other route crosses 8 or 9. Minimising the path SUM (0 → 2 → 3 → 8 → 4) or stepping to the smallest neighbour gives 8, returning the popped height t instead of the running max gives 4, and the border path along the top row gives 9.

More Coding Interview Problems questions

Exams that ask this topic