Algorithms · Visualized
DP: Min Path Sum
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Given a grid of non-negative numbers, finds the path from top-left to bottom-right (moving only right or down) that minimizes the sum of numbers along the path. Time: O(rows × cols) average, O(rows × cols) worst; space: O(rows × cols), reducible to O(cols).
Big-O: The most-asked interview category — 35 classics here.
Minimum Path Sum
Dynamic ProgrammingGiven a grid of non-negative numbers, finds the path from top-left to bottom-right (moving only right or down) that minimizes the sum of numbers along the path. dp[i][j] represents the minimum cost to reach cell (i,j), built from whichever adjacent predecessor (above or left) offers the cheaper path.
How Min Path Sum Works
- Initialize dp[0][0] to the value of the starting cell. Fill the first row by accumulating values left to right (only one way to reach these cells), and the first column by accumulating top to bottom.
- For every other cell (i, j), compute the minimum cost to arrive from above (dp[i-1][j]) or from the left (dp[i][j-1]).
- Add the current cell's own value to this minimum: dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).
- Fill the grid row by row (or column by column) in this way.
- Return the value at the bottom-right cell — the minimum path sum.
Min Path Sum Worked Example
Input: [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
First row: [1,4,5]. First column: [1,2,6]. dp[1][1]=5+min(4,2)=5+2=7. dp[1][2]=1+min(5,7)=1+5=6. dp[2][1]=2+min(7,6)=2+6=8. dp[2][2]=1+min(6,8)=1+6=7. Minimum path sum: 7 (path: 1→3→1→1→1).
def min_path_sum(grid):
rows, cols = len(grid), len(grid[0])
for c in range(1, cols):
grid[0][c] += grid[0][c - 1]
for r in range(1, rows):
grid[r][0] += grid[r - 1][0]
for c in range(1, cols):
grid[r][c] += min(grid[r - 1][c], grid[r][c - 1])
return grid[-1][-1]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Min Path Sum Time & Space Complexity
When to Use Min Path Sum
- Route/cost optimization on grid-based maps — e.g. minimizing fuel cost, terrain difficulty, or toll charges along a path.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.