Skip to content

Minimum Path Sum

Find the cheapest route from the top-left to the bottom-right of a grid, moving only right or down.

Medium2D Dynamic Programming
Solve on LeetCode

The problem

You get an m x n grid of non-negative numbers. A route starts at the top-left cell, ends at the bottom-right cell and moves only right or down. Return the smallest possible sum of the numbers on a route, counting both end cells.

Input grid = [[2, 8, 1], [3, 4, 9], [7, 1, 2]]

Output 12

Down, right, down, right visits 2, 3, 4, 1, 2, which adds up to 12.

Input grid = [[1, 9], [1, 9], [1, 1]]

Output 4

Go down the left column first, then right: 1 + 1 + 1 + 1.

Key constraint: Moves go only right or down, so a cell is entered only from above or from the left, which is what makes a simple table work.

How to spot the pattern

  • You want the cheapest route across a grid with moves in only two directions.
  • The best sum for a cell depends only on the best sums of the cell above and the cell to its left.

The idea

State: best[r][c] is the smallest sum of a route from the start to cell (r, c). You enter a cell from above or from the left, so best[r][c] = grid[r][c] + min(best[r - 1][c], best[r][c - 1]), where cells in the top row and the left column have only one way in. As in Unique Paths, each row only needs the row above it, so a single array updated from left to right is enough.

Brute force: Add up every route, and there are C(m + n - 2, m - 1) of them, which grows exponentially.

Step by step

  1. 1Make an array best with one entry per column.
  2. 2Walk the grid row by row, and each row from left to right.
  3. 3The start cell gets grid[0][0]; a top-row cell adds its value to the cell on its left, and a left-column cell adds its value to the cell above.
  4. 4Any other cell gets its value plus the smaller of best[c] (above) and best[c - 1] (left).
  5. 5Return best[n - 1] after the last row.

See the pattern move

The 2d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        # best[r][c] = grid[r][c] + min(best[r - 1][c], best[r][c - 1]); keep only the current row
        best = [0] * cols
        for r in range(rows):
            for c in range(cols):
                if r == 0 and c == 0:
                    best[c] = grid[0][0]
                elif r == 0:
                    best[c] = best[c - 1] + grid[r][c]  # top row: only from the left
                elif c == 0:
                    best[c] = best[c] + grid[r][c]  # left column: only from above
                else:
                    best[c] = min(best[c], best[c - 1]) + grid[r][c]
        return best[cols - 1]

Complexity

Time

O(m * n)

Space

O(n)

Each cell is filled once, and only one row is stored.

Watch out for

  • Stepping to the cheaper neighbor as you walk forward: a cheap step now can lead into an expensive area later.
  • Forgetting that the top row and the left column have only one way in, and reading outside the grid.

Follow-up questions

Can you use O(1) extra space?

Yes, if you may change the input: store each best value in grid itself.

What if you could move in all four directions?

Routes can then turn back, so no fill order works for the table. Since the numbers are non-negative, use Dijkstra's algorithm instead.

In Hinglish

Har cell ka best = uski value + upar aur left mein se jo chhota ho. Row by row bharo, aakhri cell mein jawab mil jayega.

Related problems