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 · Dynamic programming

The cheapest path through a grid

Medium · Target 15 minutes · Dynamic programming · Type asked atAmazonGoldman Sachs

A grid of non-negative integers gives the cost of each cell. Starting at the top-left cell and moving only right or down, reach the bottom-right cell. Return the smallest total cost of the cells on the path, including both ends.

Examples

InputOutputWhy
grid = [[1,3,1],[1,5,1],[4,2,1]]71 → 3 → 1 → 1 → 1.
grid = [[1,2,3],[4,5,6]]121 → 2 → 3 → 6.
grid = [[7]]7One cell.

Constraints

  • 1 ≤ rows, cols ≤ 200
  • 0 ≤ grid[r][c] ≤ 200

Hints

Hint 1

The last move into a cell came from above or from the left.

Hint 2

dp[r][c] = grid[r][c] + min(dp[r − 1][c], dp[r][c − 1]), with the first row and column having only one option.

Hint 3

One row of length cols is enough.

Where people lose marks

  • Using Dijkstra or breadth-first search: correct but unnecessary when moves are only right and down.
  • Treating the first row or column as reachable from outside the grid.
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.