#931

Minimum Falling Path Sum

Medium
ArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(n)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal solution uses dynamic programming to build the minimum falling path sum from the bottom row up to the top. By storing the minimum sums in the same matrix, we avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Start from the second last row and move upwards.
  2. 2Step 2: For each element, update it to be the sum of itself and the minimum of the three possible elements in the row below.
  3. 3Step 3: After processing all rows, the minimum value in the first row will be the answer.
solution.py10 lines
1# Full working Python code
2
3def minFallingPathSum(matrix):
4    n = len(matrix)
5    for row in range(n - 2, -1, -1):
6        for col in range(n):
7            matrix[row][col] += min(matrix[row + 1][col - 1] if col > 0 else float('inf'),
8                                   matrix[row + 1][col],
9                                   matrix[row + 1][col + 1] if col < n - 1 else float('inf'))
10    return min(matrix[0])

Complexity note: The time complexity remains O(n²) because we still iterate through all elements of the matrix. However, the space complexity is O(1) since we are modifying the input matrix in place.

  • 1Dynamic programming can significantly reduce redundant calculations.
  • 2In-place updates can save space while solving the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.