LeetCode #64 Medium

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.

Constraints
  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200
dpgrid
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minPathSum(self, grid):
▶3 m, n = len(grid), len(grid[0])
▶4 dp = [float("inf")] * n
▶5 dp[0] = 0
▶6 for i in range(m):
▶7 for j in range(n):
▶8 left = dp[j - 1] if j > 0 else float("inf")
▶9 dp[j] = grid[i][j] + min(dp[j], left)
▶10 return dp[n - 1]
grid131151421best cost per column0∞∞ways infrom abovefrom leftcellcheapercostseed the start with 0, the rest unknown
dp[0, ∞, ∞]one row of costs
The cost row starts as infinity everywhere except a 0 in column 0. The 0 lets the top-left cell cost exactly its own value; the infinities stand for the space above the grid, which no path can come from.
grid131151421best cost per column1∞∞ways infrom above0from left∞cellcheapercost1+0=1start cell → cost 1
cellrow 0, col 0
dp[1, ∞, ∞]column 0 now 1
The top-left cell is where every path begins, so the seeded 0 is the only way in and its cost is just its value, 1. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column14∞ways infrom above∞from left1cellcheapercost3+1=4only from the left → cost 4
cellrow 0, col 1
dp[1, 4, ∞]column 1 now 4
Nothing lies above the top row, so the only way in is from the left neighbour, which costs 1. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column145ways infrom above∞from left4cellcheapercost1+4=5only from the left → cost 5
cellrow 0, col 2
dp[1, 4, 5]column 2 now 5
Nothing lies above the top row, so the only way in is from the left neighbour, which costs 4. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column245ways infrom above1from left∞cellcheapercost1+1=2only from above → cost 2
cellrow 1, col 0
dp[2, 4, 5]column 0 now 2
Column 0 has nothing on its left, so the only way in is from above, where the slot still holds 1 from the previous row. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column275ways infrom above4from left2cellcheapercost5+2=7left is cheaper → cost 7
cellrow 1, col 1
dp[2, 7, 5]column 1 now 7
The slot under this column still holds 4, the cost of the cell above. The slot to its left was already updated this row to 2. The cheaper is 2, so this cell costs 5 + 2 = 7. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column276ways infrom above5from left7cellcheapercost1+5=6above is cheaper → cost 6
cellrow 1, col 2
dp[2, 7, 6]column 2 now 6
The slot under this column still holds 5, the cost of the cell above. The slot to its left was already updated this row to 7. The cheaper is 5, so this cell costs 1 + 5 = 6. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column676ways infrom above2from left∞cellcheapercost4+2=6only from above → cost 6
cellrow 2, col 0
dp[6, 7, 6]column 0 now 6
Column 0 has nothing on its left, so the only way in is from above, where the slot still holds 2 from the previous row. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column686ways infrom above7from left6cellcheapercost2+6=8left is cheaper → cost 8
cellrow 2, col 1
dp[6, 8, 6]column 1 now 8
The slot under this column still holds 7, the cost of the cell above. The slot to its left was already updated this row to 6. The cheaper is 6, so this cell costs 2 + 6 = 8. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column687ways infrom above6from left8cellcheapercost1+6=7above is cheaper → cost 7
cellrow 2, col 2
dp[6, 8, 7]column 2 now 7
The slot under this column still holds 6, the cost of the cell above. The slot to its left was already updated this row to 8. The cheaper is 6, so this cell costs 1 + 6 = 7. It overwrites the old value in the same slot, which the row no longer needs.
grid131151421best cost per column687ways infrom abovefrom leftcellcheapercostanswer: 7
result7
The last slot holds the cost of the bottom-right cell, 7. Walking back from that corner, always to the cheaper of the cell above and the cell on the left, recovers one cheapest path, shown in green.
05

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.

▶1from functools import cache
▶2 
▶3class Solution:
▶4 def minPathSum(self, grid):
▶5 @cache
▶6 def best(i, j):
▶7 if i < 0 or j < 0:
▶8 return float("inf")
▶9 if i == 0 and j == 0:
▶10 return grid[0][0]
▶11 return grid[i][j] + min(best(i - 1, j), best(i, j - 1))
▶12 
▶13 return best(len(grid) - 1, len(grid[0]) - 1)
06

Common pitfalls

Stepping to the cheaper neighbour as you walk

✗ Wrong
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]
✓ Right
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

✗ Wrong
dp = [0] * n
✓ Right
dp = [float("inf")] * n
dp[0] = 0

Zeros 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.

07

Complexity

Time
O(m · n)
Space
O(n)
Every cell is visited once and does two lookups. Only one row of n costs is kept. Writing the costs straight into grid would bring extra space to O(1), but it changes the caller's input.
08

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.