Minimum Path Sum

Minimum sum from top-left to bottom-right moving right/down — 1D rolling DP.

Medium
Time O(m * n) Space O(n)
LeetCode
3 min read
dp grid

Problem#

Min sum of a path from (0,0) to (m-1,n-1) moving only right or down.

Examples#

  • [[1,3,1],[1,5,1],[4,2,1]]7

Constraints#

  • 1 <= m, n <= 200.

Approach#

dp[c] = min sum to reach row’s column c. Each new row: dp[c] = grid[r][c] + min(dp[c], dp[c-1]) (top vs left).

Solution#

Minimum Path Sum
class Solution {
public:
int minPathSum(vector<vector<int>>& g) {
int m = g.size(), n = g[0].size();
vector<int> dp(n, INT_MAX);
dp[0] = 0;
for (int r = 0; r < m; ++r) {
dp[0] += g[r][0];
for (int c = 1; c < n; ++c) {
dp[c] = g[r][c] + min(dp[c], dp[c - 1]);
}
}
return dp[n - 1];
}
};

Editorial#

Rolling 1D: dp[c] from the previous row holds “top”, dp[c-1] from the current row holds “left”. The first column is updated explicitly (no left predecessor).

Complexity#

  • Time: O(m * n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.