Minimum Path Sum
Minimum Path Sum is a medium dynamic programming problem solved with the 2d dp pattern.
The best approach, optimal (one row), runs in O(m · n) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from recursion up.
Problem
Find a path from the top-left to the bottom-right of a grid of non-negative numbers, moving only right or down, that minimises the sum of the numbers along it.
Examples
Example 1
- Input
grid = [[1,3,1],[1,5,1],[4,2,1]]- Output
7- Why
- 1 → 3 → 1 → 1 → 1.
Example 2
- Input
grid = [[1,2,3],[4,5,6]]- Output
12
Constraints
1 <= m, n <= 200; values 0 to 200.- Move only right or down.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Recursion | O(2^(m + n)) | O(m + n) |
| Tabulation (2D table) | O(m · n) | O(m · n) |
| Optimal (one row) | O(m · n) | O(n) |
1Recursion
O(2^(m + n))O(m + n)The cheapest path into (i, j) comes from above or from the left.
- cost(0, 0) = grid[0][0]; out of bounds = infinity.
- cost(i, j) = grid[i][j] + min(cost(i - 1, j), cost(i, j - 1)).
class Solution {
public int minPathSum(int[][] grid) {
return cost(grid, grid.length - 1, grid[0].length - 1);
}
private int cost(int[][] g, int i, int j) {
if (i < 0 || j < 0) return Integer.MAX_VALUE;
if (i == 0 && j == 0) return g[0][0];
return g[i][j] + Math.min(cost(g, i - 1, j), cost(g, i, j - 1));
}
}class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
return self.cost(grid, len(grid) - 1, len(grid[0]) - 1)
def cost(self, g: List[List[int]], i: int, j: int) -> float:
if i < 0 or j < 0:
return math.inf
if i == 0 and j == 0:
return g[0][0]
return g[i][j] + min(self.cost(g, i - 1, j), self.cost(g, i, j - 1))class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
return cost(grid, grid.size() - 1, grid[0].size() - 1);
}
private:
int cost(vector<vector<int>>& g, int i, int j) {
if (i < 0 || j < 0) return INT_MAX;
if (i == 0 && j == 0) return g[0][0];
return g[i][j] + min(cost(g, i - 1, j), cost(g, i, j - 1));
}
};function minPathSum(grid) {
function cost(g, i, j) {
if (i < 0 || j < 0) return Infinity;
if (i === 0 && j === 0) return g[0][0];
return g[i][j] + Math.min(cost(g, i - 1, j), cost(g, i, j - 1));
}
return cost(grid, grid.length - 1, grid[0].length - 1);
}2Tabulation (2D table)
O(m · n)O(m · n)Fill the table row by row. The first row and first column each have only one way in.
- dp[0][0] = grid[0][0]; fill the first row and column with running sums.
- dp[i][j] = grid[i][j] + min(up, left).
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) dp[i][j] = grid[0][0];
else if (i == 0) dp[i][j] = dp[i][j - 1] + grid[i][j];
else if (j == 0) dp[i][j] = dp[i - 1][j] + grid[i][j];
else dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
}
return dp[m - 1][n - 1];
}
}class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[0][0]
elif i == 0:
dp[i][j] = dp[i][j - 1] + grid[i][j]
elif j == 0:
dp[i][j] = dp[i - 1][j] + grid[i][j]
else:
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
return dp[m - 1][n - 1]class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) dp[i][j] = grid[0][0];
else if (i == 0) dp[i][j] = dp[i][j - 1] + grid[i][j];
else if (j == 0) dp[i][j] = dp[i - 1][j] + grid[i][j];
else dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]);
}
return dp[m - 1][n - 1];
}
};function minPathSum(grid) {
const m = grid.length, n = grid[0].length;
const dp = Array.from({ length: m }, () => new Array(n).fill(0));
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++) {
if (i === 0 && j === 0) dp[i][j] = grid[0][0];
else if (i === 0) dp[i][j] = dp[i][j - 1] + grid[i][j];
else if (j === 0) dp[i][j] = dp[i - 1][j] + grid[i][j];
else dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
}
return dp[m - 1][n - 1];
}3Optimal (one row)
O(m · n)O(n)Keep a single row. Before updating, dp[j] still holds the value from the row above, and dp[j - 1] already holds the new value to the left.
- dp[j] = grid[i][j] + min(dp[j] (up), dp[j - 1] (left)).
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[] dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
dp[j] = grid[i][j] + (j == 0 ? dp[0] : Math.min(dp[j], dp[j - 1]));
return dp[n - 1];
}
}class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = [math.inf] * n
dp[0] = 0
for i in range(m):
for j in range(n):
dp[j] = grid[i][j] + (dp[0] if j == 0 else min(dp[j], dp[j - 1]))
return dp[n - 1]class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<int> dp(n, INT_MAX);
dp[0] = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
dp[j] = grid[i][j] + (j == 0 ? dp[0] : min(dp[j], dp[j - 1]));
return dp[n - 1];
}
};function minPathSum(grid) {
const m = grid.length, n = grid[0].length;
const dp = new Array(n).fill(Infinity);
dp[0] = 0;
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++)
dp[j] = grid[i][j] + (j === 0 ? dp[0] : Math.min(dp[j], dp[j - 1]));
return dp[n - 1];
}Edge cases to test
- Single row or single column
Hints
Hint 1
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]).
FAQ
What is the best time complexity for Minimum Path Sum?
Optimal (one row) runs in O(m · n) time and O(n) extra space.
Which pattern does Minimum Path Sum use?
It is a dynamic programming problem that uses the 2d dp pattern. Other problems with the same pattern: Unique Paths, Unique Paths II, Dungeon Game.
Is there a brute force solution for Minimum Path Sum?
Yes. Recursion takes O(2^(m + n)) time and O(m + n) space. The cheapest path into (i, j) comes from above or from the left.
Which edge cases should I test for Minimum Path Sum?
Single row or single column.