Minimum Path Cost in a Grid solution explained
Minimum Path Cost in a Grid asks for the cheapest route from any cell in the top row to any cell in the bottom row, moving one row down at a time to any column, where a route pays for every cell it visits plus a price for each move that depends on the cell you leave and the column you enter. Solve it with row-by-row dynamic programming: the best cost of ending on a cell is its value plus the cheapest way to arrive from any cell in the row above. That is O(R × C²) time and O(C) extra space.
By Evin JohnPublished 9 min read
The problem, in plain terms
You have a grid with R rows and C columns. Every cell holds a different whole number from 0 to R × C - 1. You also get a price table with one line per possible cell value and one entry per column: the entry for value v and column j is what it costs to move from the cell holding v to column j of the next row. A route starts on any cell of the first row, then moves down one row at a time, landing on any column it likes, until it reaches the last row. Its cost is the sum of all the cells it stands on plus all the move prices it paid. Return the cheapest possible cost.
grid price to move to column 1 column 2
3 0 from value 0 8 8
5 1 from value 1 9 9
2 4 from value 3 2 4
from value 5 7 1
(values 2 and 4 are in the last row, so their lines are never read)
best route: 3 (column 1) -> 5 (column 1) -> 4 (column 2)
cells 3 + 5 + 4 = 12, moves 2 + 1 = 3, total 15Before coding, confirm three things: whether the price depends on the value of the cell you leave (it does here, which is why every value is distinct), whether the last row pays any move price (it does not), and whether costs can be negative. Repeat the rule back in one sentence, because the indexing is where most bugs come from.
How it differs from Minimum Path Sum
Minimum Path Sum moves right or down from a fixed corner to a fixed corner and only pays for cells. Here the start and end are free, each step jumps to any column of the next row, and the moves themselves cost something. The DP idea is the same family, but every cell now has C possible predecessors instead of two, so a row costs C² work instead of C. Interviewers use this one to check that you can read an unusual cost rule carefully and turn it into a recurrence without mixing up indexes.
Why the cheapest next step is not enough
A greedy walk would start on the smallest cell of the first row and, at each row, jump to whichever column makes move price plus cell value smallest. On the example it starts on 0, which looks ideal, but every move out of 0 costs 8. It lands on 1 (8 + 1), and every move out of 1 costs 9, so it finishes on 2 for a total of 0 + 8 + 1 + 9 + 2 = 20. Starting on the larger 3 unlocks cheap moves and gives 15. Cheap cells can sit behind expensive exits, so local choices mislead.
Brute force
A route is just a list of R column choices, so there are C to the power R routes. Trying them all and adding up each one costs O(C^R × R). That is fine as a test reference on a few rows and hopeless beyond that, but saying it out loud shows the interviewer you understand what a route is before you optimize.
The optimal approach: row-by-row DP
Pattern: layered dynamic programming. Let best[c] be the cheapest cost of any route that ends on column c of the current row, counting that cell. For the first row it is the cell value itself, since a route may start anywhere. For each later row, the cost of ending on column c is the cell's value plus the minimum, over every column p of the row above, of best[p] plus the price of moving from the value in that cell to column c. When the last row is done, the answer is the smallest entry of best. The routes only ever move downward, so the rows form a graph without cycles and no ordering issues come up.
def min_path_cost(grid, move_cost):
rows, cols = len(grid), len(grid[0])
best = grid[0][:] # cheapest path ending at each cell of the current row
for r in range(1, rows):
nxt = []
for c in range(cols):
cheapest_way_in = min(
best[p] + move_cost[grid[r - 1][p]][c] for p in range(cols)
)
nxt.append(cheapest_way_in + grid[r][c])
best = nxt
return min(best)Tracing the example: the first row gives best = [3, 0]. For the second row, column 1 costs 5 plus the smaller of 3 + 2 and 0 + 8, which is 10, and column 2 costs 1 plus the smaller of 3 + 4 and 0 + 8, which is 8. For the third row, column 1 is 2 + min(10 + 7, 8 + 9) = 19 and column 2 is 4 + min(10 + 1, 8 + 9) = 15. The answer is 15.
Recovering the route in JavaScript
The JavaScript version pushes costs forward from each cell of the row above instead of pulling them, which reads naturally when you think of the moves as edges. It also stores, for every cell, the column it was reached from, then walks back from the cheapest cell in the last row to return the full list of columns.
function minPathCost(grid, moveCost) {
const rows = grid.length, cols = grid[0].length;
let best = grid[0].slice();
const from = []; // from[r][c]: column used in row r - 1
for (let r = 1; r < rows; r++) {
const next = new Array(cols).fill(Infinity);
from.push(new Array(cols).fill(-1));
for (let p = 0; p < cols; p++) { // push forward from each cell above
const leaving = grid[r - 1][p];
for (let c = 0; c < cols; c++) {
const total = best[p] + moveCost[leaving][c] + grid[r][c];
if (total < next[c]) {
next[c] = total;
from[r - 1][c] = p;
}
}
}
best = next;
}
let col = 0;
for (let c = 1; c < cols; c++) if (best[c] < best[col]) col = c;
const columns = [col];
for (let r = rows - 1; r >= 1; r--) {
col = from[r - 1][col];
columns.push(col);
}
return { cost: Math.min(...best), columns: columns.reverse() };
}On the example this returns a cost of 15 and the zero-based columns [0, 0, 1]. Keeping the parent table costs O(R × C) memory, which is the price of being able to show the route.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Every column sequence | O(C^R × R) | O(R) for the current sequence |
| Greedy cheapest next step | O(R × C), but wrong | O(1) |
| Row-by-row DP, cost only | O(R × C²) | O(C) |
| Row-by-row DP with route recovery | O(R × C²) | O(R × C) |
You can also see the grid as a layered graph and run a shortest-path algorithm such as Dijkstra's. It gives the same answer when prices are non-negative, but it adds a heap and a log factor for no benefit, because the layers already give a valid processing order. Mentioning that you considered it, and why the DP is simpler, is a good senior signal.
Edge cases to test
- One row: no moves happen, so the answer is the smallest value in that row.
- One column: every move goes straight down, and the answer is the sum of the column plus each move price into column 1.
- Move prices of 0 everywhere, where the problem reduces to picking the smallest cell in each row.
- A cheap first-row cell whose exits are all expensive, like the example.
- A tall grid, to make sure the array is sized by columns and reused across rows.
Common mistakes
- Indexing the price table by the column of the cell you leave instead of by its value.
- Indexing it by the value of the cell you enter instead of the column you enter.
- Adding a move price after the last row, which has nowhere to go.
- Starting every route in column 1, or initializing the first row with zeros instead of its cell values.
- Overwriting best while still reading the previous row from it; build the new row in a separate array.
How to explain it out loud
Fictional example
- Candidate
- Let me restate the cost: every cell I stand on counts, and every jump down costs an amount looked up by the value I'm leaving and the column I'm landing in. Nothing is charged after the last row.
- Candidate
- I'll keep, for each column, the cheapest route that ends there in the current row. The first row is just the cell values, because I can start anywhere.
- Candidate
- Each new cell takes the minimum over all C cells above, plus the move and its own value. That's R times C squared time and one array of size C. If you want the actual route, I'll keep a parent column per cell.
Related problems
Two routes planned together on the same grid, with cells that pay out only once, is Cherry Pickup. A DP that walks a string instead of a grid, choosing between one-character and two-character steps, is Decode Ways II.
Natively during your prep
Problems with a custom cost rule reward reading slowly, which is easy to skip under a timer. When you practice on Mac or Windows, Natively can take a screenshot of the statement and price table and write an approach and code you can hold up against your own indexing. It also keeps a transcript of the session, so you can check whether you restated the rule before writing the recurrence. Read how AI helps in coding interviews.
Questions people ask
How do you solve Minimum Path Cost in a Grid?
Go row by row. The best cost of ending on a cell is its value plus the cheapest, over every cell in the row above, of that cell's best cost plus the price of moving from its value to this column. The answer is the smallest cost in the last row.
What is the time complexity of Minimum Path Cost in a Grid?
O(R × C²) for R rows and C columns, because each of the R × C cells looks at all C cells above it. Extra space is O(C) when you keep only one row of costs.
How is Minimum Path Cost in a Grid different from Minimum Path Sum?
Minimum Path Sum moves right or down between two fixed corners and only pays for cells. Here you start and end in any column, jump to any column of the next row, and pay a price for each move as well.
Can you use Dijkstra's algorithm for Minimum Path Cost in a Grid?
Yes, with non-negative prices it gives the same answer, but the rows already form a natural order, so a plain DP is simpler and avoids the heap's extra log factor.
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.
