Minimum Path Sum
Minimum Path Sum is LeetCode 64 (Medium). You get an m × n grid of non-negative numbers. A path starts in the top-left cell, moves only right or down, and ends in the bottom-right cell.
- The cost of a path is the sum of every cell it touches, the first and last cells included.
- Return the smallest cost of any such path.
A 200 × 200 grid has more paths than can ever be listed, so each cell must be worked out once and reused.
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 200
- 0 <= grid[i][j] <= 200
Intuition
A cell can only be entered from the cell above it or the cell to its left. So the cheapest way to reach a cell is its own value plus the cheaper of those two neighbours' cheapest costs. That one rule turns the grid into a fill-in table:
- Top row: a cell has no neighbour above, so its cost is the running total along the row.
- Left column: a cell has no neighbour on the left, so its cost is the running total down the column.
- Any other cell: its value plus min(cost above, cost on the left).
Fill the table row by row, left to right, and both neighbours are always finished before the cell that needs them. The bottom-right entry is the answer.
A grid, a fixed start and end corner, moves limited to right and down, and a total to minimise: that is grid dynamic programming. Unique Paths counts the same routes instead of pricing them, and Triangle uses the same "best of the cells that lead here" rule.
Approach
Before reading on, list the cells a path can come from when it enters cell (i, j), then pick a fill order that finishes both of them first. Aim for O(m·n) time and a single row of extra memory.
Two ways to solve it
Fill costs in reading order, reusing one row.
- No recursion: a plain double loop.
- Small memory: one row of
nnumbers.
The usual interview answer.
Ask for the cost of the bottom-right cell; it asks its top and left neighbours, and a cache stops any cell being solved twice.
- Natural first idea: it is the recurrence written down directly.
- Costs more: a full cache plus a call stack up to m + n deep.
Both solve every cell once. The table version wins because it needs one row of memory and no call stack. The steps, code and live demo use the table, and the recursive code follows the demo.
Keep one row of costs
Make an array dp of length n. While row i is being filled, dp[j] still holds the cost of the cell directly above until it is overwritten, so one row stores everything the next cell needs.
Seed the starting corner
Fill dp with infinity and set dp[0] = 0. The 0 makes the top-left cell come out as just its own value, and infinity means the empty space above the first row never wins a comparison.
Fill each cell from its two neighbours
For cell (i, j), the cost from above is the old dp[j] and the cost from the left is dp[j - 1], which this row has already updated. Set dp[j] = grid[i][j] + min(dp[j], left), treating left as infinity in column 0.
Read the bottom-right cost
After the last row, return dp[n - 1]. Each cell was computed only from cells that were already final, so no cost ever has to be revised.
Code in Python, C++ and Java
Memoized recursion
best(i, j) is the cheapest cost from the top-left corner to cell (i, j). It is the cell's value plus the smaller of best(i - 1, j) and best(i, j - 1); stepping outside the grid returns infinity, so that direction never wins. The cache means each cell is computed once.
Common pitfalls
Stepping to the cheaper neighbour as you walk
i = j = 0
cost = grid[0][0]
while i < m - 1 or j < n - 1:
if j == n - 1 or (i < m - 1 and grid[i + 1][j] < grid[i][j + 1]):
i += 1
else:
j += 1
cost += grid[i][j]dp[j] = grid[i][j] + min(dp[j], left)
A cheap step now can lead into an expensive part of the grid. On [[1,1,9],[2,8,9],[1,1,1]] the walk goes right to 1, then has to pick between 9 and 8, and finishes with cost 12. Going down first costs 1 + 2 + 1 + 1 + 1 = 6.
Filling the row with zeros
dp = [0] * n
dp = [float("inf")] * n
dp[0] = 0Zeros pretend there is a free row above the grid. Every top-row cell then takes cost 0 from "above" instead of the running total from the left, so [[1, 2, 3]] returns 3 instead of 6.
Complexity
n costs is kept. Writing the costs straight into grid would bring extra space to O(1), but it changes the caller's input.Minimum Path Sum FAQ
How do I get the path itself, not just its cost?
Keep the full m × n table of costs instead of one row. Start at the bottom-right cell and keep stepping to whichever of the cell above or the cell to the left has the smaller cost, until you reach the top-left. Reverse the cells you passed through.
What changes if the path may also move up or left?
Cells can then feed each other in loops, so no fill order finishes a cell's neighbours first. Since all values are non-negative, Dijkstra's algorithm on the grid still finds the cheapest path, in O(m·n log(m·n)) time.