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

The path with the least effort

Medium · Target 25 minutes · Graphs · Type asked atGoogleAmazon

A grid gives the height of each cell. You start at the top-left cell and must reach the bottom-right cell, moving up, down, left or right. The effort of a route is the largest absolute difference in height between two consecutive cells on it. Return the minimum effort over all routes.

Examples

InputOutputWhy
heights = [[1,2,2],[3,8,2],[5,3,5]]2Down the left side and along the bottom: every step changes height by at most 2.
heights = [[1,2,3],[3,8,4],[5,3,5]]1Along the top and down the right side, one unit at a time.
heights = [[7]]0Already there.

Constraints

  • 1 ≤ rows, cols ≤ 100
  • 1 ≤ heights[r][c] ≤ 10⁶

Hints

Hint 1

A route's cost is not a sum, it is the maximum step along it. Extending a route can only keep that maximum or raise it.

Hint 2

That property is all Dijkstra needs. Keep the best effort found for each cell and always settle the cell with the smallest.

Hint 3

When you move from a cell with effort e into a neighbour, the neighbour's candidate effort is max(e, |height difference|).

Where people lose marks

  • Summing the differences, which answers a different question.
  • Plain breadth-first search, which minimises the number of steps, not the effort.
  • Stopping when the target is first pushed rather than when it is popped.
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.