Minimum Path Sum - Problem
Minimum Path Sum

You are given an m x n grid filled with non-negative numbers. Your goal is to find a path from the top-left corner to the bottom-right corner that minimizes the sum of all numbers along the path.

Movement Rules:
• You can only move right or down at any point
• You cannot move diagonally, left, or up

Example:
For grid [[1,3,1],[1,5,1],[4,2,1]], the minimum path sum is 7 following the path: 1→3→1→1→1

Input & Output

example_1.py — Basic 3x3 Grid
$ Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
💡 Note: The path 1→3→1→1→1 gives minimum sum of 7. Alternative paths like 1→1→5→1→1 would give sum of 9, which is larger.
example_2.py — 2x3 Grid
$ Input: grid = [[1,2,3],[4,5,6]]
Output: 12
💡 Note: The minimum path is 1→2→3→6, giving sum of 12. Going 1→4→5→6 would give 16.
example_3.py — Single Element
$ Input: grid = [[5]]
Output: 5
💡 Note: Edge case: grid with only one element. The minimum (and only) path sum is the element itself.

Constraints

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

Visualization

Tap to expand
Minimum Path Sum - Dynamic Programming INPUT m x n Grid (3x3) 1 3 1 1 5 1 4 2 1 START END Movement Rules: Only RIGHT or DOWN Right Down [[1,3,1],[1,5,1],[4,2,1]] ALGORITHM STEPS 1 Create DP Table dp[i][j] = min sum to (i,j) 2 Initialize First Row/Col Cumulative sums (one path) 3 Fill DP Table dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]) 4 Return Answer dp[m-1][n-1] = result DP Table: 1 4 5 2 7 6 6 8 7 FINAL RESULT Optimal Path Highlighted: 1 3 1 1 5 1 4 2 1 Path: 1 --> 3 --> 1 --> 1 --> 1 Sum: 1 + 3 + 1 + 1 + 1 OUTPUT 7 OK - Verified Key Insight: Each cell's minimum path sum depends only on the cells above and to the left (optimal substructure). The DP recurrence dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]) builds the solution bottom-up. Time: O(m*n) | Space: O(1) if modifying input grid, O(m*n) otherwise TutorialsPoint - Minimum Path Sum | Dynamic Programming Approach
Asked in
Amazon 42 Google 38 Microsoft 31 Apple 28 Meta 25 Bloomberg 19
73.9K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen