Minimum Path Sum solution explained
To find the cheapest route from the top-left to the bottom-right of a number grid when you may only move right or down, use dynamic programming: the cheapest cost to reach any cell is its own value plus the smaller of the cheapest costs to reach the cell above it and the cell to its left. Fill the costs row by row and read the answer from the last cell. That is O(R × C) time and, with a single reused row, O(C) extra space.
By Evin JohnPublished 8 min read
The problem, in plain terms
Every cell of a rectangular grid holds a number, usually a non-negative cost. Start on the top-left cell and finish on the bottom-right one. Each step goes one cell right or one cell down, never up or left. The cost of a route is the sum of every cell on it, including the first and last. Return the smallest possible cost.
2 9 1
4 3 8
7 1 2
cheapest route: 2 -> 4 -> 3 -> 1 -> 2 (down, right, down, right)
total: 12
cost to reach each cell (the DP table):
2 11 12
6 9 17
13 10 12Questions to ask: can values be negative, can the grid be a single row or column, do you need the route or only its cost, and may you overwrite the input grid. Overwriting the grid with running costs saves memory, but some interviewers consider changing the input a side effect, so say what you are doing.
Why it is a good dynamic programming opener
The recurrence is easy to state, the table is small enough to fill by hand on a whiteboard, and the space optimization is a natural next question. It also has a tempting wrong answer, the greedy walk, which gives the interviewer a chance to see whether you test an idea before committing to it. Interviewers usually want to hear the subproblem defined in words before any code.
Why greedy fails
A greedy walk that always steps to the cheaper of the two next cells looks reasonable and is wrong. On the grid below it takes the cheap 1 to the right, then gets stuck paying 8 and 9, for a total of 20. The best route goes down first and costs 6. A cheap step now can lead into an expensive region, so local choices are not enough.
1 1 8
2 9 9
1 1 1
greedy: 1 -> 1 -> 8 -> 9 -> 1 = 20
best: 1 -> 2 -> 1 -> 1 -> 1 = 6Brute force, then memoization
The brute force tries every route. A grid with R rows and C columns has C(R + C - 2, R - 1) of them, which grows exponentially, so plain recursion that explores both moves from every cell is far too slow beyond small grids. The fix is to notice that the cheapest cost to reach a cell does not depend on how you got there, so it can be computed once and reused. Adding a cache to the recursion turns it into the dynamic programming solution.
from functools import lru_cache
def min_path_sum_memo(grid):
@lru_cache(maxsize=None)
def best(r, c): # cheapest cost to reach (r, c) from the top-left
if r == 0 and c == 0:
return grid[0][0]
options = []
if r > 0:
options.append(best(r - 1, c))
if c > 0:
options.append(best(r, c - 1))
return grid[r][c] + min(options)
return best(len(grid) - 1, len(grid[0]) - 1)The optimal approach: bottom-up with one row
Fill costs from the top-left forward. The first row can only be reached from the left, the first column only from above, and every other cell takes the cheaper of the two. Since each row needs only the row above it, a single array of length C is enough: before you update best[c], it still holds the cost of the cell above, and best[c - 1] already holds the updated cost of the cell to the left.
def min_path_sum(grid):
cols = len(grid[0])
best = [0] * cols # best[c] = cheapest cost to reach row r, column c
for r, row in enumerate(grid):
for c, val in enumerate(row):
if r == 0 and c == 0:
best[c] = val
elif r == 0:
best[c] = best[c - 1] + val
elif c == 0:
best[c] = best[c] + val
else:
best[c] = min(best[c], best[c - 1]) + val
return best[-1]When the interviewer also wants the route, keep the whole table and walk backward from the bottom-right corner, each time stepping to whichever of the cell above or the cell to the left has the smaller cost. The JavaScript version below does that and returns both the total and the list of cells.
// Returns the cheapest total and one cheapest route as [row, col] pairs.
function minPathWithRoute(grid) {
const rows = grid.length, cols = grid[0].length;
const cost = grid.map((row) => row.slice());
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (r === 0 && c === 0) continue;
const up = r > 0 ? cost[r - 1][c] : Infinity;
const left = c > 0 ? cost[r][c - 1] : Infinity;
cost[r][c] += Math.min(up, left);
}
}
const route = [];
let r = rows - 1, c = cols - 1;
while (r > 0 || c > 0) { // walk back along whichever side was cheaper
route.push([r, c]);
if (c === 0 || (r > 0 && cost[r - 1][c] <= cost[r][c - 1])) r--;
else c--;
}
route.push([0, 0]);
return { total: cost[rows - 1][cols - 1], route: route.reverse() };
}On the first example grid this returns a total of 12 and the route (0,0), (1,0), (1,1), (2,1), (2,2). Copying the grid with slice keeps the caller's grid unchanged.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Try every route | O(C(R + C - 2, R - 1) × (R + C)) | O(R + C) recursion |
| Recursion with a cache | O(R × C) | O(R × C) cache plus O(R + C) stack |
| Bottom-up full table, with route recovery | O(R × C) | O(R × C) |
| Bottom-up single row | O(R × C) | O(C), or O(min(R, C)) by iterating the shorter side |
Negative values and other moves
Because routes only go right or down, no cell can be revisited and the grid behaves like a graph without cycles, so the same DP is correct even when some values are negative. That changes if moves in all four directions are allowed. Then cells can depend on each other in circles, the DP order no longer works, and the problem becomes a shortest-path search such as Dijkstra's algorithm, which needs non-negative costs.
Edge cases to test
- A one-by-one grid, where the answer is that single value.
- A single row or a single column, where there is only one route.
- Ties between the cell above and the cell to the left.
- Zeros throughout, and a grid with some negative values.
- A tall, narrow grid, to check that the row array uses the column count.
Common mistakes
- Going greedy, as shown above.
- Initializing the first row and column with 0 or with the grid values instead of running sums, which lets routes appear to enter from outside the grid.
- Forgetting to add the starting cell's own value, or the final cell's.
- Writing min(best[c], best[c - 1]) for c = 0, which in Python reads best[-1], the last column, and gives wrong answers without an error.
- Sizing the single row by the number of rows when the grid is not square.
How to explain it out loud
Fictional example
- Candidate
- Picking the cheaper next step doesn't work, because a cheap step can lead into an expensive area. So I'll define cost of a cell as the cheapest way to reach it from the start.
- Candidate
- Since I can only come from above or from the left, that cost is the cell's value plus the smaller of those two costs. The first row and column only have one way in, so they're running sums.
- Candidate
- I fill row by row, and because each row only needs the one above, I can keep a single array. That's R times C time and C extra space. If you want the path, I'll keep the full table and walk back from the corner.
Related problems
Moving through a grid in every direction rather than only right and down turns the task into search, as in Flood Fill. For a grid answer that comes from counting instead of choosing, see Island Perimeter.
Natively for DP practice
Dynamic programming answers fall apart when the subproblem is fuzzy, so practice saying it in one sentence. Natively runs on Mac and Windows; in your practice sessions it can read a grid problem from a screenshot, suggest a recurrence to compare with yours, and help trace a table that comes out wrong. Its transcript lets you check whether you defined the state before you started coding. Read about AI help for LeetCode-style practice.
Questions people ask
How do you solve Minimum Path Sum?
Use dynamic programming. The cheapest cost to reach a cell is its value plus the smaller of the costs to reach the cell above and the cell to the left. Fill the grid row by row and return the bottom-right cost.
What is the time and space complexity of Minimum Path Sum?
O(R × C) time. Space is O(R × C) for a full table, or O(C) when you keep a single row and update it in place.
Why does a greedy approach fail?
Taking the cheaper next cell can lead into an expensive part of the grid that a slightly costlier first step would have avoided. The DP compares all routes without listing them.
Does Minimum Path Sum work with negative numbers?
Yes, as long as moves are only right and down, because no cell can be revisited. If moves in all four directions were allowed, it would become a shortest-path problem instead.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
