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.
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.
A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).
Example 1:
Input: matrix = [[2,1,3],[6,5,4],[7,8,9]] Output: 13 Explanation: There are two falling paths with a minimum sum as shown.
Example 2:
Input: matrix = [[-19,57],[-40,-5]] Output: -59 Explanation: The falling path with a minimum sum is shown.
Constraints:
n == matrix.length == matrix[i].length1 <= n <= 100-100 <= matrix[i][j] <= 100Problem summary: Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[[2,1,3],[6,5,4],[7,8,9]]
[[-19,57],[-40,-5]]
minimum-falling-path-sum-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #931: Minimum Falling Path Sum
class Solution {
public int minFallingPathSum(int[][] matrix) {
int n = matrix.length;
var f = new int[n];
for (var row : matrix) {
var g = f.clone();
for (int j = 0; j < n; ++j) {
if (j > 0) {
g[j] = Math.min(g[j], f[j - 1]);
}
if (j + 1 < n) {
g[j] = Math.min(g[j], f[j + 1]);
}
g[j] += row[j];
}
f = g;
}
// return Arrays.stream(f).min().getAsInt();
int ans = 1 << 30;
for (int x : f) {
ans = Math.min(ans, x);
}
return ans;
}
}
// Accepted solution for LeetCode #931: Minimum Falling Path Sum
func minFallingPathSum(matrix [][]int) int {
n := len(matrix)
f := make([]int, n)
for _, row := range matrix {
g := make([]int, n)
copy(g, f)
for j, x := range row {
if j > 0 {
g[j] = min(g[j], f[j-1])
}
if j+1 < n {
g[j] = min(g[j], f[j+1])
}
g[j] += x
}
f = g
}
return slices.Min(f)
}
# Accepted solution for LeetCode #931: Minimum Falling Path Sum
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
f = [0] * n
for row in matrix:
g = [0] * n
for j, x in enumerate(row):
l, r = max(0, j - 1), min(n, j + 2)
g[j] = min(f[l:r]) + x
f = g
return min(f)
// Accepted solution for LeetCode #931: Minimum Falling Path Sum
struct Solution;
impl Solution {
fn min_falling_path_sum(a: Vec<Vec<i32>>) -> i32 {
let n = a.len();
let m = a[0].len();
let mut dp = vec![vec![0; m]; n];
for i in 0..n {
for j in 0..m {
let mut min = std::i32::MAX;
if i > 0 {
let l = 0.max(j as i32 - 1) as usize;
let r = (n - 1).min(j + 1);
for k in l..=r {
min = min.min(dp[i - 1][k]);
}
} else {
min = 0;
}
dp[i][j] = a[i][j] + min;
}
}
*dp[n - 1].iter().min().unwrap()
}
}
#[test]
fn test() {
let a = vec_vec_i32![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let res = 12;
assert_eq!(Solution::min_falling_path_sum(a), res);
}
// Accepted solution for LeetCode #931: Minimum Falling Path Sum
function minFallingPathSum(matrix: number[][]): number {
const n = matrix.length;
const f: number[] = new Array(n).fill(0);
for (const row of matrix) {
const g = f.slice();
for (let j = 0; j < n; ++j) {
if (j > 0) {
g[j] = Math.min(g[j], f[j - 1]);
}
if (j + 1 < n) {
g[j] = Math.min(g[j], f[j + 1]);
}
g[j] += row[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.