Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Swim in rising water

Hard · Target 30 minutes · Graphs · Type asked atGoogleAmazon

An n × n grid holds distinct elevations from 0 to n² − 1. At time t the water is at depth t everywhere, and you can swim between adjacent cells (up, down, left, right) only if both are at elevation at most t. Swimming itself takes no time. Starting at the top-left cell, return the least time at which you can reach the bottom-right cell.

Examples

InputOutputWhy
grid = [[0,2],[1,3]]3The target itself is at elevation 3, so nothing earlier can work.
grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]16The spiral along the edge and into row 2 never goes above 16.
grid = [[0]]0Already there.

Constraints

  • 1 ≤ n ≤ 50
  • The elevations are a permutation of 0 … n² − 1

Hints

Hint 1

The time a route becomes usable is the highest elevation on it, including the start and the end.

Hint 2

So you want the route whose highest cell is lowest: a minimax path, which Dijkstra handles with max in place of +.

Hint 3

Start with the cost of the start cell itself, and relax a neighbour with max(cost so far, its elevation).

Where people lose marks

  • Forgetting that the start cell's own elevation counts: the answer is at least grid[0][0].
  • Counting the number of steps: swimming takes no time.
  • Breadth-first search by steps, which finds the shortest route, not the lowest one.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.