InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Minimum Path Sum

medium Original β†—
Solving tips
  • Classic grid path DP: dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]), since a cell is only reachable from above or from the left.
  • Initialize the first row and first column as running prefix sums (they have a single predecessor each) before filling the interior.
  • Only right/down moves are legal, so read exactly the two neighbors above and to the left β€” no diagonal or upward transitions.
  • Target O(m*n) time, O(n) space with one rolling row updated left-to-right (dp[j]=above, dp[j-1]=left).

Problem

Given an m x n grid filled with non-negative integers, find a path from the top-left cell to the bottom-right cell that minimizes the sum of the numbers along it. You may only move right or down at each step.

Return that minimum sum.

Examples

  • [[1, 3, 1], [1, 5, 1], [4, 2, 1]] β†’ 7 β€” the path 1 β†’ 3 β†’ 1 β†’ 1 β†’ 1 (right, right, down, down) sums to 7.
  • [[1, 2, 3], [4, 5, 6]] β†’ 12 β€” 1 β†’ 2 β†’ 3 β†’ 6 sums to 12; going down early costs more.
  • [[5]] β†’ 5 β€” a single cell; the path is just that cell.

Constraints

  • m == grid.length, n == grid[0].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200

Enumerating all right/down paths is exponential (there are C(m+n, m) of them); the expected solution is O(m Γ— n).

Think about it first

Hint 1 Every cell is reached from either the cell directly above or the cell directly to its left β€” those are the only two moves. So the cheapest way to reach a cell is its own value plus the cheaper of those two predecessors.
Hint 2 Let `dp[i][j]` be the minimum path sum to reach cell `(i, j)` from the top-left. That's a 2-D table filled top-to-bottom, left-to-right.
Hint 3 `dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1])`. The first row and first column have only one predecessor each (a running prefix sum). The answer is `dp[m-1][n-1]`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.