Minimum Falling Path Sum II

Hard

Topics
ArrayDynamic ProgrammingMatrix

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

012314562789012
Pick exactly one cell per row so that no two consecutive picks share a column. The shaded picks sum to 13, the minimum.
2D grid — one row per line.
Input:  grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13

Example 2

070
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

  1. Start with the first row as the running state.
  2. For each later row, find the smallest value in the previous row, its column, and the second smallest.
  3. Set each column to its own value plus the smallest, except the argmin column which uses the second smallest.
  4. 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 elif branch, 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)
SensAI
Beta
Tap the mic to stop voice mode