← Back to index
MediumPython3 min read

Minimum Path Sum

find minimum sum path from top-left to bottom-right using dynamic programming with space optimization.

dynamic-programmingmatrix

Problem link

View on LeetCode

Solutions in this repo

  • Python../minimum-path-sum/solution.pyPython solution

dp[i][j] = minimum sum to reach (i,j). can only move right or down. dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).

optimize space to O(n) by using only one row. update row from left to right, carrying previous row values.

optimization

since we only need previous row and current position, we can use single array and update in-place. reduces space from O(mn) to O(n).

complexity

O(mn) time, O(n) space where m and n are grid dimensions. efficient dp solution.