Minimum Falling Path Sum II — LeetCode 1289 Python Solution

HardArrayDynamic ProgrammingMatrix
Problem
#1289
Reading time
2 min

The problem

Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.

Example

Input
grid = [[1,2,3],[4,5,6],[7,8,9]]
Output
13
Explanation
The possible falling paths are:

Python solution

Python
class Solution:
    def minFallingPathSum(self, grid: List[List[int]]) -> int:
        n = len(grid)
        f = [0] * n
        for row in grid:
            g = row[:]
            for i in range(n):
                g[i] += min((f[j] for j in range(n) if j != i), default=0)
            f = g
        return min(f)

Complexity

MeasureComplexity
TimeO(n^3)
SpaceO(n^2) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1289. Minimum Falling Path Sum II is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1289. Minimum Falling Path Sum II?
LeetCode 1289. Minimum Falling Path Sum II is rated Hard on LeetCode.
What is the time complexity of LeetCode 1289. Minimum Falling Path Sum II?
The Python solution on this page runs in O(n^3).
What is the space complexity of LeetCode 1289. Minimum Falling Path Sum II?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 1289. Minimum Falling Path Sum II cover?
LeetCode 1289. Minimum Falling Path Sum II is tagged Array, Dynamic Programming and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview