Minimum Falling Path Sum II
Hard
Topics
Given an n x n integer grid, a falling path with non-zero shifts chooses exactly one element from each row such that no two chosen elements in adjacent rows are in the same column. Return the minimum sum of such a falling path.
Example 1
Input: grid = [[1,2,3],[4,5,6],[7,8,9]] Output: 13
Example 2
Input: grid = [[7]] Output: 7
Constraints
- n == grid.length == grid[i].length
- 1 <= n <= 200
- -99 <= grid[i][j] <= 99
Editorial — intuition, approach, complexity and pitfalls
Intuition
The constraint is only that adjacent rows use different columns. So when building row r, every column needs the best value from row r-1 excluding its own column.
Computing that exclusion by scanning the previous row per column is O(n) each, giving O(n³) overall. But the excluded minimum takes only two values: for every column except the argmin, it is the row minimum; for the argmin itself, it is the second smallest. So tracking the two smallest values of the previous row, and where the smallest sits, collapses the inner loop to O(1).
Approach
- Start with the first row as the running state.
- For each later row, find the smallest value in the previous row, its column, and the second smallest.
- Set each column to its own value plus the smallest, except the argmin column which uses the second smallest.
- The answer is the minimum of the final row.
Dry Run
grid = [[1,2,3],
[4,5,6],
[7,8,9]]
row 0 state [1, 2, 3]
row 1 smallest 1 at column 0, second smallest 2
column 0 must avoid column 0, so it uses 2 -> 4 + 2 = 6
columns 1 and 2 use 1 -> 5 + 1 = 6, 6 + 1 = 7
state [6, 6, 7]
row 2 smallest 6 at column 0, second smallest 6
column 0 uses the second smallest 6 -> 7 + 6 = 13
columns 1 and 2 use 6 -> 8 + 6 = 14, 9 + 6 = 15
state [13, 14, 15]
answer 13
row 2 is the case worth noticing: the smallest and second smallest are both 6,
which is fine -- they are different positions, and that is all the rule needs.Complexity
- Time — O(n²): two linear passes per row.
- Space — O(n): one row of state. The full table is unnecessary since each row reads only its predecessor.
Common Pitfalls
- Scanning the previous row for each column, which is the O(n³) version. At n = 200 it still passes, so this one hides well.
- Tracking only the minimum. The argmin column has to use something else, and without the second smallest there is nothing to use.
- Requiring the two smallest to be distinct values. They need only be distinct positions — row 2 above has two 6s and the answer is still correct.
- Updating the two smallest while writing the new row, so later columns see partially updated state. Compute them from the previous row first, then build.
- Initialising the second smallest to the same variable as the first, or forgetting the
elifbranch, which leaves it at infinity when the row happens to be sorted. - Assuming a single-column grid needs handling. The grid is square, so one column implies one row and the loop never runs — worth checking rather than assuming, since the two-smallest logic would otherwise return infinity.
Full Solution — all languages
class Solution:
def minFallingPathSum(self, grid):
R = len(grid)
C = len(grid[0])
prev = grid[0][:]
for r in range(1, R):
m1 = float('inf'); i1 = -1; m2 = float('inf')
for c in range(C):
if prev[c] < m1:
m2 = m1; m1 = prev[c]; i1 = c
elif prev[c] < m2:
m2 = prev[c]
cur = [0] * C
for c in range(C):
cur[c] = grid[r][c] + (m2 if c == i1 else m1)
prev = cur
return min(prev)import java.util.*;
class Solution {
public int minFallingPathSum(int[][] grid) {
int R = grid.length, C = grid[0].length;
int[] prev = grid[0].clone();
for (int r = 1; r < R; r++) {
int m1 = Integer.MAX_VALUE, i1 = -1, m2 = Integer.MAX_VALUE;
for (int c = 0; c < C; c++) {
if (prev[c] < m1) {
m2 = m1;
m1 = prev[c];
i1 = c;
} else if (prev[c] < m2) m2 = prev[c];
}
int[] cur = new int[C];
for (int c = 0; c < C; c++) cur[c] = grid[r][c] + (c == i1 ? m2 : m1);
prev = cur;
}
int ans = Integer.MAX_VALUE;
for (int v : prev) ans = Math.min(ans, v);
return ans;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minFallingPathSum(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
vector<int> prev = grid[0];
for (int r = 1; r < R; r++) {
int m1 = INT_MAX, i1 = -1, m2 = INT_MAX;
for (int c = 0; c < C; c++) {
if (prev[c] < m1) {
m2 = m1;
m1 = prev[c];
i1 = c;
} else if (prev[c] < m2) m2 = prev[c];
}
vector<int> cur(C);
for (int c = 0; c < C; c++) cur[c] = grid[r][c] + (c == i1 ? m2 : m1);
prev = cur;
}
return *min_element(prev.begin(), prev.end());
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var minFallingPathSum = function(grid) {
const R = grid.length, C = grid[0].length;
let prev = grid[0].slice();
for (let r = 1; r < R; r++) {
let m1 = Infinity, i1 = -1, m2 = Infinity;
for (let c = 0; c < C; c++) {
if (prev[c] < m1) {
m2 = m1;
m1 = prev[c];
i1 = c;
} else if (prev[c] < m2) m2 = prev[c];
}
const cur = new Array(C);
for (let c = 0; c < C; c++) cur[c] = grid[r][c] + (c === i1 ? m2 : m1);
prev = cur;
}
return Math.min.apply(null, prev);
};