Minimum Path Sum (LeetCode 64): Solution and Explanation
A grid holds non-negative numbers. Starting at the top-left cell and moving only right or down, find the path to the bottom-right cell whose values add up to the smallest total.
Watch it run step by step
Try your own input and write the code →Intuition
Trying every path is hopeless at scale. An m by n grid has a number of monotone paths equal to a binomial coefficient that grows exponentially, and a plain recursion that explores right and down from each cell recomputes the same subpaths again and again.
The way out is to notice that the moves only go right or down, so any cell can only be entered from the cell above it or the cell to its left. If you already know the cheapest total to reach each of those two neighbors, the cheapest total to reach the current cell is the smaller of the two plus the cell's own value. That is the recurrence dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j], and it works because the best path to a cell must use a best path to whichever neighbor it came from.
The edges need special care. The first row can only be reached by moving right along it, so each of its entries is a running sum from the left. The first column can only be reached by moving down, so its entries are a running sum from the top. With those filled in, every interior cell has both neighbors ready if you fill row by row from left to right.
The answer sits in the bottom-right corner of the table. Because the grid has no negative values and every step moves closer to the target, there are no cycles to worry about, which is why simple dynamic programming works here instead of a shortest path algorithm like Dijkstra's.
Approach: 2D bottom-up dynamic programming
- Record
mandn, create an m by n tabledp, and setdp[0][0] = grid[0][0]. - Fill the first column with running sums:
dp[i][0] = dp[i-1][0] + grid[i][0]. - Fill the first row with running sums:
dp[0][j] = dp[0][j-1] + grid[0][j]. - For every other cell, row by row, set
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]. - Return
dp[m-1][n-1], the cheapest total to reach the bottom-right cell.
Step-by-step example
grid = [[1,3,1],[1,5,1],[4,2,1]]
- The top-left value is 1. The first column becomes 1, 2, 6 and the first row becomes 1, 4, 5.
- Cell (1,1): the smaller of above (4) and left (2) is 2, plus 5 gives 7.
- Cell (1,2): the smaller of above (5) and left (7) is 5, plus 1 gives 6.
- Cell (2,1): the smaller of above (7) and left (6) is 6, plus 2 gives 8.
- Cell (2,2): the smaller of above (6) and left (8) is 6, plus 1 gives 7.
- The answer is 7, from the path 1, 3, 1, 1, 1 along the top row and down the right column.
Code: Python, Java, C++
1class Solution:
2 def minPathSum(self, grid: List[List[int]]) -> int:
3 m, n = len(grid), len(grid[0])
4 dp = [[0] * n for _ in range(m)]
5 dp[0][0] = grid[0][0]
6
7 for i in range(1, m):
8 dp[i][0] = dp[i-1][0] + grid[i][0]
9 for j in range(1, n):
10 dp[0][j] = dp[0][j-1] + grid[0][j]
11
12 for i in range(1, m):
13 for j in range(1, n):
14 dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
15
16 return dp[m-1][n-1]1class Solution {
2 public int minPathSum(int[][] grid) {
3 int m = grid.length, n = grid[0].length;
4 int[][] dp = new int[m][n];
5 dp[0][0] = grid[0][0];
6
7 for (int i = 1; i < m; i++) dp[i][0] = dp[i-1][0] + grid[i][0];
8 for (int j = 1; j < n; j++) dp[0][j] = dp[0][j-1] + grid[0][j];
9
10 for (int i = 1; i < m; i++) {
11 for (int j = 1; j < n; j++) {
12 dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
13 }
14 }
15 return dp[m-1][n-1];
16 }
17}1class Solution {
2public:
3 int minPathSum(vector<vector<int>>& grid) {
4 int m = grid.size(), n = grid[0].size();
5 vector<vector<int>> dp(m, vector<int>(n, 0));
6 dp[0][0] = grid[0][0];
7
8 for (int i = 1; i < m; i++) dp[i][0] = dp[i-1][0] + grid[i][0];
9 for (int j = 1; j < n; j++) dp[0][j] = dp[0][j-1] + grid[0][j];
10
11 for (int i = 1; i < m; i++) {
12 for (int j = 1; j < n; j++) {
13 dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
14 }
15 }
16 return dp[m-1][n-1];
17 }
18};Time and space complexity
O(m × n)
Every cell of the grid is filled exactly once, and each fill does a constant amount of work.
O(m × n)
The dp table has the same shape as the grid. Since each row only depends on the row above, a single row of length n is enough if memory matters.
Other approaches
One-row DP (time O(m × n), space O(n))
Keep a single array of length n. For each new row, update it left to right, where the old value at j is the cell above and the new value at j - 1 is the cell to the left. The recurrence is unchanged, and memory drops to one row.
In-place DP on the grid (time O(m × n), space O(1))
Overwrite grid itself with the running minimums instead of allocating a table. It uses no extra memory, but it destroys the input, which is not acceptable if the caller still needs it.
Common mistakes
- Taking the min of above and left on the first row or first column, where one of those neighbors does not exist. Those edges must be filled with running sums first.
- Using a greedy rule that always steps toward the smaller neighbor. A cheap next cell can lead into an expensive region, so local choices do not give the global minimum.
- Forgetting to add
grid[i][j]itself, which returns the cost of the path up to but not including the current cell. - Swapping
mandnwhen the grid is not square, which raises an index error on rectangular inputs.
Frequently asked questions
Why does dynamic programming work for Minimum Path Sum?
Each cell can only be reached from above or from the left. The cheapest path to a cell therefore extends the cheapest path to one of those two neighbors, so each value can be built from smaller, already solved subproblems.
Can Minimum Path Sum be solved with O(n) space?
Yes. Each row only needs the row above it, so a single array of length n can be updated in place row by row, keeping the same O(m × n) time.
Why not use Dijkstra's algorithm for Minimum Path Sum?
It would work, but it is unnecessary. Because moves only go right or down, the grid has a natural order in which every cell's predecessors are processed first, so a simple DP pass is faster and simpler.