HardNo. 1289

Minimum Falling Path Sum II — LeetCode 1289 Python Solution

Topics
Array, Dynamic Programming, Matrix
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

PythonSolution
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

Time
O(n3)
Space · auxiliary
O(n2)

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

Related problems
No.ProblemDifficulty
0931Minimum Falling Path SumMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard
0174Dungeon GameHard
0221Maximal SquareMedium

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

What is the space complexity of LeetCode 1289. Minimum Falling Path Sum II?

The Python solution on this page uses O(n2) 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.

Free to download. Check it runs on your machine, then pick a plan.