LeetCode #931 Medium

Minimum Falling Path Sum

Minimum Falling Path Sum is LeetCode 931 (Medium). You get a square n × n matrix of integers, and some of them may be negative. A falling path picks one cell in the top row, then one cell in every row below it, ending in the bottom row.

  • From column j, the next cell must be in column j - 1, j or j + 1 of the next row.
  • The sum of a path is the total of its n cells.

Return the smallest sum any falling path can have. Each row can triple the number of paths, so listing them is hopeless even at n = 100.

Constraints
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 100
  • -100 <= matrix[i][j] <= 100
dynamic-programmingarraymatrix
Open on LeetCode ↗
02

Intuition

Think about where a path was one row earlier. A path that ends on cell (i, j) came from at most three cells: up-left, straight up, or up-right. If we already know the cheapest fall that ends at each cell of row i - 1, then the cheapest fall ending at (i, j) is matrix[i][j] plus the smallest of those three.

The top row is free: a fall that ends there is just that one cell. Each later row is built from the finished row above it, so the whole matrix is covered in one pass. The path may stop in any column, so the answer is the smallest value in the last row, not one fixed cell.

How to spot this pattern

Choose one item per row, where each choice limits the next one to nearby positions, and minimise the total: that is row-by-row dynamic programming. Triangle (LeetCode 120) and Minimum Falling Path Sum II (LeetCode 1289) change only which cells of the previous row are allowed.

03

Approach

Try it first

Before reading on, decide what number you would store for each cell so that the next row can be computed from it alone, and how you would handle the first and last columns. Aim for O(n²) time and O(n) memory.

1

Start from a copy of the top row

Set prev = matrix[0][:]. A fall that ends in the top row has only that one cell, so these values are already final, and copying them leaves the input untouched.

2

Price each cell of the next row

For column j, start with prev[j], and also consider prev[j - 1] and prev[j + 1] when those columns exist. Write matrix[i][j] plus the smallest into a new array cur. The first and last columns have only two cells above them.

3

Move down one row

Set prev = cur and repeat for every row. Only the row directly above is ever read, so two arrays of n numbers are all the memory the loop needs.

4

Pick the best ending column

After the last row, prev[j] is the cheapest fall that ends in column j. Return min(prev), because the problem lets the path finish in any column of the bottom row.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minFallingPathSum(self, matrix):
▶3 n = len(matrix)
▶4 prev = matrix[0][:]
▶5 for i in range(1, n):
▶6 cur = [0] * n
▶7 for j in range(n):
▶8 best_above = prev[j]
▶9 if j > 0:
▶10 best_above = min(best_above, prev[j - 1])
▶11 if j < n - 1:
▶12 best_above = min(best_above, prev[j + 1])
▶13 cur[j] = matrix[i][j] + best_above
▶14 prev = cur
▶15 return min(prev)
cell value · cheapest fall to it221133654789cell valuebest above+fall sum=top row: each fall is just its cell
prev[2, 1, 3]copy of the top row
A fall that ends in the top row has used only that one cell, so the top row's costs are its own values. Every later row is built from the row above it.
cell value · cheapest fall to it2211336754789cell value6best above1+fall sum7=2 above, best up-right → 7
cellrow 1, col 0
cur[0]76 + 1
A fall reaching this cell came from one of only two cells, because column 0 is at the edge in the row above, whose cheapest falls are 2, 1. The smallest is 1 (up-right), so the cheapest fall ending here costs 6 + 1 = 7.
cell value · cheapest fall to it22113367564789cell value5best above1+fall sum6=3 above, best straight up → 6
cellrow 1, col 1
cur[1]65 + 1
A fall reaching this cell came from one of three cells in the row above, whose cheapest falls are 2, 1, 3. The smallest is 1 (straight up), so the cheapest fall ending here costs 5 + 1 = 6.
cell value · cheapest fall to it221133675645789cell value4best above1+fall sum5=2 above, best up-left → 5
cellrow 1, col 2
cur[2]54 + 1
A fall reaching this cell came from one of only two cells, because column 2 is at the edge in the row above, whose cheapest falls are 1, 3. The smallest is 1 (up-left), so the cheapest fall ending here costs 4 + 1 = 5.
cell value · cheapest fall to it22113367564571389cell value7best above6+fall sum13=2 above, best up-right → 13
cellrow 2, col 0
cur[0]137 + 6
A fall reaching this cell came from one of only two cells, because column 0 is at the edge in the row above, whose cheapest falls are 7, 6. The smallest is 6 (up-right), so the cheapest fall ending here costs 7 + 6 = 13.
cell value · cheapest fall to it2211336756457138139cell value8best above5+fall sum13=3 above, best up-right → 13
cellrow 2, col 1
cur[1]138 + 5
A fall reaching this cell came from one of three cells in the row above, whose cheapest falls are 7, 6, 5. The smallest is 5 (up-right), so the cheapest fall ending here costs 8 + 5 = 13.
cell value · cheapest fall to it221133675645713813914cell value9best above5+fall sum14=2 above, best straight up → 14
cellrow 2, col 2
cur[2]149 + 5
A fall reaching this cell came from one of only two cells, because column 2 is at the edge in the row above, whose cheapest falls are 6, 5. The smallest is 5 (straight up), so the cheapest fall ending here costs 9 + 5 = 14.
cell value · cheapest fall to it221133675645713813914cell valuebest above+fall sum=smallest in the last row: 13
result13
The path may end in any column, so the answer is the smallest value in the last row, 13. Following each cell's best source back up gives the path in green.
05

Common pitfalls

Overwriting the row you are still reading

✗ Wrong
for j in range(n):
    best = min(prev[max(j - 1, 0):j + 2])
    prev[j] = matrix[i][j] + best
✓ Right
for j in range(n):
    best = min(prev[max(j - 1, 0):j + 2])
    cur[j] = matrix[i][j] + best
prev = cur

By the time column j + 1 is priced, prev[j] already holds the new row's value, so a cell can count two cells from the same row. On [[-1,-2,-2],[-3,-1,0],[1,0,0]] this returns -6 instead of -5.

Letting column -1 wrap around

✗ Wrong
best = min(prev[j - 1], prev[j], prev[j + 1] if j + 1 < n else prev[j])
✓ Right
best = prev[j]
if j > 0:
    best = min(best, prev[j - 1])
if j < n - 1:
    best = min(best, prev[j + 1])

In Python prev[-1] is the last column, so column 0 silently reads a cell on the far side instead of failing. On [[3,0,-3],[-1,0,1],[0,-4,2]] this returns -8 instead of -7.

Starting the answer at 0

✗ Wrong
ans = 0
for v in prev:
    ans = min(ans, v)
✓ Right
ans = min(prev)

A falling path must use one cell in every row, so its sum is often positive. On [[2,1,3],[6,5,4],[7,8,9]] the 0 is never beaten and the result is 0 instead of 13.

06

Edge cases

A 1 × 1 matrix such as [[-7]]

The loop over later rows never runs, and the answer is the minimum of the top row, -7.

07

Complexity

Time
O(n²)
Space
O(n)
Each of the n² cells compares at most three numbers from the row above. Two rows of n numbers are stored at any moment.
08

Minimum Falling Path Sum FAQ

How is this different from Minimum Path Sum?

Minimum Path Sum (LeetCode 64) starts in a fixed corner, moves right or down, and ends in a fixed corner, so each cell has two sources and the answer is one cell. Here the path may start and end in any column, each cell has up to three sources directly above it, and the answer is the minimum over a whole row.

What changes in Minimum Falling Path Sum II?

In LeetCode 1289 the next cell may be in any column except the same one. Keep the smallest and second-smallest values of the row above: a cell adds the smallest unless it sits in that same column, in which case it adds the second-smallest. That keeps the work at O(n²).

Why not start at the smallest cell of the top row?

The cheapest start can lead into expensive rows. In [[1,2,3],[9,9,1],[9,9,9]] starting at 1 forces 9 and 9 for a total of 19, while starting at 2 allows 2 + 1 + 9 = 12. The row-by-row table keeps every start alive until the end.