Minimum Path Sum

Medium

Topics
ArrayDynamic ProgrammingMatrix

Given an m x n grid filled with non-negative numbers, find a path from the top-left to the bottom-right which minimises the sum of all numbers along the path.

You can only move either down or right at any point in time.

Example 1

013111512421012
Only moves right and down are allowed, so every route is a staircase from the top-left to the bottom-right. The shaded staircase is the cheapest one; its values add up to 7.
2D grid — one row per line.
Input:  grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: The path 1 -> 3 -> 1 -> 1 -> 1 has the minimum sum.

Example 2

01231456012
Input:  grid = [[1,2,3],[4,5,6]]
Output: 12

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every cell can only be entered from above or from the left, so the cheapest way to reach a cell is its own value plus the cheaper of those two predecessors. That is a complete recurrence with no choices left over, which means one pass over the grid in row-major order computes every answer exactly once.

Approach

  1. Let dp[i][j] be the minimum sum of any path from the origin to cell (i, j).
  2. The first row can only be reached by moving right, so it is a running prefix sum. The first column is the same going down.
  3. For every other cell, dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).
  4. The answer is dp[m-1][n-1]. Because each row depends only on the previous one, you can collapse the table to a single row of length n.
class Solution:
    def minPathSum(self, grid):
        m, n = len(grid), len(grid[0])
        dp = [0] * n
        dp[0] = grid[0][0]
        for j in range(1, n):
            dp[j] = dp[j - 1] + grid[0][j]
        for i in range(1, m):
            dp[0] += grid[i][0]
            for j in range(1, n):
                dp[j] = grid[i][j] + min(dp[j], dp[j - 1])
        return dp[-1]

Dry Run

grid  1 3 1
      1 5 1
      4 2 1
One rolling row, reused in place. Each cell is "cheapest way to arrive here".
  row 0   start 1 | left only 1+3=4 | left only 4+1=5        row [1, 4, 5]
  row 1   above only 1+1=2
          min(above 4, left 2) + 5 = 7
          min(above 5, left 7) + 1 = 6                       row [2, 7, 6]
  row 2   above only 2+4=6
          min(above 7, left 6) + 2 = 8
          min(above 6, left 8) + 1 = 7                       row [6, 8, 7]
answer 7   --  the path 1 -> 3 -> 1 -> 1 -> 1
The first row and first column need their own branches because they have no left
or no upper neighbour. Initialise them to zero and the costs of getting to the
edges are simply lost.
This problem is greedy-proof, and the page's own grid proves it. Always stepping
to the smaller neighbour goes 1 -> 1 (down) -> 4 (down) -> 2 -> 1 and totals 9,
where the optimum is 7: the cheap first step into the left column leads straight
into the 4. A cheap step can lead into an expensive region, which is exactly why
every cell has to be evaluated.
In the rolling row, `best[c]` is read before it is written, so at that moment it
still holds the value from the row above while `best[c-1]` already holds this
row's. One array, two rows' worth of information.

Complexity

  • Time — O(m x n) — each cell is resolved once.
  • Space — O(n) — one rolling row; O(m x n) if you keep the full table.

Common Pitfalls

  • Do not initialise the first row or column to zero — they have no left or upper neighbour, so they need their own prefix-sum pass.
  • This problem is greedy-proof, and the page's own example proves it. Always stepping toward the smaller neighbour goes 1, 1, 4, 2, 1 for a total of 9 where the optimum is 7: the cheap first step down leads straight into the 4. A cheap step can lead into an expensive region.
  • For the follow-ups, see Dungeon Game (fill backwards) and Cherry Pickup II (two simultaneous paths).

Full Solution — all languages

class Solution:
    def minPathSum(self, grid):
        rows, cols = len(grid), len(grid[0])
        best = [0] * cols
        for r in range(rows):
            for c in range(cols):
                if r == 0 and c == 0:
                    best[c] = grid[r][c]
                elif r == 0:
                    best[c] = best[c - 1] + grid[r][c]
                elif c == 0:
                    best[c] = best[c] + grid[r][c]
                else:
                    best[c] = min(best[c], best[c - 1]) + grid[r][c]
        return best[cols - 1]
Asked at Goldman Sachs
SensAI
Beta
Tap the mic to stop voice mode