Community Problem

Minimum Falling Path Sum

Difficulty: Medium

Find the minimum sum of a top-to-bottom path in a square matrix where each step moves to one of three cells directly below, using row-by-row DP.

Minimum Falling Path Sum

Find the minimum sum of a top-to-bottom path in a square matrix where each step moves to one of three cells directly below, using row-by-row DP.

MEDIUM
Free
dynamic-programming
grid-dp
matrix-algorithms
averyperry

By @averyperry

January 1, 2026

·

Updated May 18, 2026

1,001 views

22

4.3 (10)

I had this on a Datadog onsite and it's a textbook grid-DP, but the framing matters: the natural recurrence walks DOWN the matrix (dp[r][c] = matrix[r][c] + min(dp[r-1][c-1], dp[r-1][c], dp[r-1][c+1])), and once you see that, the whole O(n^2) solution falls out in ten lines. The catalog covered minimum-path-sum (which only allows down/right) but it skipped the (c-1, c, c+1) falling variant.

Minimum Falling Path Sum

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).

Examples

Example 1:

  • Input: matrix = [[2, 1, 3], [6, 5, 4], [7, 8, 9]]
  • Output: 13
  • Explanation: One falling path with minimum sum is 1 -> 4 -> 8. (Or 1 -> 5 -> 7 for 13, or 2 -> 5 -> 7 for 14.)

Example 2:

  • Input: matrix = [[-19, 57], [-40, -5]]
  • Output: -59
  • Explanation: Path -19 -> -40 sums to -59.

Example 3:

  • Input: matrix = [[7]]
  • Output: 7
  • Explanation: A 1x1 matrix has the trivial path [7].

Example 4:

  • Input: matrix = [[1, 2, 3], [-100, 100, 100], [100, 100, 100]]
  • Output: 1
  • Explanation: Walk 1 -> -100 -> 100, summing to 1. (2 -> -100 -> 100 also yields 2, but 1 -> -100 -> 100 wins.)

Constraints

  • n == matrix.length.
  • n == matrix[i].length.
  • 1 <= n <= 100.
  • -100 <= matrix[i][j] <= 100.

Follow-up

Can you solve this in O(n) extra space? Yes. The recurrence only depends on the previous row, so a single rolling array of size n suffices. Either keep two arrays and swap, or do the row update in place from left to right while temporarily saving the old dp[r-1][c] value before overwriting.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems