Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from cells in the last row.
Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored.
The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row.
Example 1:
Input: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]] Output: 17 Explanation: The path with the minimum possible cost is the path 5 -> 0 -> 1. - The sum of the values of cells visited is 5 + 0 + 1 = 6. - The cost of moving from 5 to 0 is 3. - The cost of moving from 0 to 1 is 8. So the total cost of the path is 6 + 3 + 8 = 17.
Example 2:
Input: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]] Output: 6 Explanation: The path with the minimum possible cost is the path 2 -> 3. - The sum of the values of cells visited is 2 + 3 = 5. - The cost of moving from 2 to 3 is 1. So the total cost of this path is 5 + 1 = 6.
Constraints:
m == grid.lengthn == grid[i].length2 <= m, n <= 50grid consists of distinct integers from 0 to m * n - 1.moveCost.length == m * nmoveCost[i].length == n1 <= moveCost[i][j] <= 100Problem summary: You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from cells in the last row. Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored. The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[[5,3],[4,0],[2,1]] [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]
[[5,1,2],[4,0,3]] [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]
unique-paths)unique-paths-ii)minimum-path-sum)dungeon-game)paint-house)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2304: Minimum Path Cost in a Grid
class Solution {
public int minPathCost(int[][] grid, int[][] moveCost) {
int m = grid.length, n = grid[0].length;
int[] f = grid[0];
final int inf = 1 << 30;
for (int i = 1; i < m; ++i) {
int[] g = new int[n];
Arrays.fill(g, inf);
for (int j = 0; j < n; ++j) {
for (int k = 0; k < n; ++k) {
g[j] = Math.min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]);
}
}
f = g;
}
// return Arrays.stream(f).min().getAsInt();
int ans = inf;
for (int v : f) {
ans = Math.min(ans, v);
}
return ans;
}
}
// Accepted solution for LeetCode #2304: Minimum Path Cost in a Grid
func minPathCost(grid [][]int, moveCost [][]int) int {
m, n := len(grid), len(grid[0])
f := grid[0]
for i := 1; i < m; i++ {
g := make([]int, n)
for j := 0; j < n; j++ {
g[j] = 1 << 30
for k := 0; k < n; k++ {
g[j] = min(g[j], f[k]+moveCost[grid[i-1][k]][j]+grid[i][j])
}
}
f = g
}
return slices.Min(f)
}
# Accepted solution for LeetCode #2304: Minimum Path Cost in a Grid
class Solution:
def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = grid[0]
for i in range(1, m):
g = [inf] * n
for j in range(n):
for k in range(n):
g[j] = min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j])
f = g
return min(f)
// Accepted solution for LeetCode #2304: Minimum Path Cost in a Grid
impl Solution {
pub fn min_path_cost(grid: Vec<Vec<i32>>, move_cost: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
let mut f = grid[0].clone();
for i in 1..m {
let mut g: Vec<i32> = vec![i32::MAX; n];
for j in 0..n {
for k in 0..n {
g[j] = g[j].min(f[k] + move_cost[grid[i - 1][k] as usize][j] + grid[i][j]);
}
}
f.copy_from_slice(&g);
}
f.iter().cloned().min().unwrap_or(0)
}
}
// Accepted solution for LeetCode #2304: Minimum Path Cost in a Grid
function minPathCost(grid: number[][], moveCost: number[][]): number {
const m = grid.length;
const n = grid[0].length;
const f = grid[0];
for (let i = 1; i < m; ++i) {
const g: number[] = Array(n).fill(Infinity);
for (let j = 0; j < n; ++j) {
for (let k = 0; k < n; ++k) {
g[j] = Math.min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]);
}
}
f.splice(0, n, ...g);
}
return Math.min(...f);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.