Minimum Falling Path Sum — LeetCode 931 Python Solution

MediumArrayDynamic ProgrammingMatrix
Problem
#931
Reading time
2 min

The problem

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.

Example

Input
matrix = [[2,1,3],[6,5,4],[7,8,9]]
Output
13
Explanation
There are two falling paths with a minimum sum as shown.

Python solution

Python
class Solution:
    def minFallingPathSum(self, matrix: List[List[int]]) -> int:
        n = len(matrix)
        f = [0] * n
        for row in matrix:
            g = [0] * n
            for j, x in enumerate(row):
                l, r = max(0, j - 1), min(n, j + 2)
                g[j] = min(f[l:r]) + x
            f = g
        return min(f)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 931. Minimum Falling Path Sum 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 931. Minimum Falling Path Sum?
LeetCode 931. Minimum Falling Path Sum is rated Medium on LeetCode.
What topics does LeetCode 931. Minimum Falling Path Sum cover?
LeetCode 931. Minimum Falling Path Sum 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