KatInterview

967. Minimum Falling Path Sum

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum sum of a "falling path" in an n x n grid. A falling path starts from any cell in the first row and moves to the next row by choosing a cell that is either directly below, or diagonally to the left or right. This problem has optimal substructure and overlapping subproblems, making it a classic candidate for dynamic programming.

Solution

Minimum Falling Path Sum in Python

class Solution:
    def minFallingPathSum(self, matrix: List[List[int]]) -> int:
        n = len(matrix)
        if n == 0:
            return 0

        # We can use the matrix itself as the DP table to save space.
        # matrix[i][j] will store the minimum falling path sum ending at (i, j).

        # Iterate from the second row to the end.
        for i in range(1, n):
            for j in range(n):
                # Find the minimum path sum from the previous row.
                # The previous cell can be (i-1, j-1), (i-1, j), or (i-1, j+1).

                # Start with the cell directly above.
                min_prev = matrix[i-1][j]

                # Check the diagonally left cell.
                if j > 0:
                    min_prev = min(min_prev, matrix[i-1][j-1])
                
                # Check the diagonally right cell.
                if j < n - 1:
                    min_prev = min(min_prev, matrix[i-1][j+1])
                
                # Update the current cell's value with the minimum path sum.
                matrix[i][j] += min_prev

        # The result is the minimum value in the last row.
        return min(matrix[n-1])

Minimum Falling Path Sum in Java

class Solution {
    public int minFallingPathSum(int[][] matrix) {
        int n = matrix.length;
        if (n == 0) {
            return 0;
        }

        // We use the matrix itself as the DP table to achieve O(1) space.
        // matrix[i][j] will store the minimum falling path sum ending at (i, j).

        // Iterate from the second row to the end.
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                // Find the minimum path sum from the previous row.
                // The previous cell can be (i-1, j-1), (i-1, j), or (i-1, j+1).

                // Start with the cell directly above.
                int minPrev = matrix[i-1][j];

                // Check the diagonally left cell.
                if (j > 0) {
                    minPrev = Math.min(minPrev, matrix[i-1][j-1]);
                }

                // Check the diagonally right cell.
                if (j < n - 1) {
                    minPrev = Math.min(minPrev, matrix[i-1][j+1]);
                }

                // Update the current cell's value with the minimum path sum.
                matrix[i][j] += minPrev;
            }
        }

        // The result is the minimum value in the last row.
        int minSum = matrix[n-1][0];
        for (int j = 1; j < n; j++) {
            minSum = Math.min(minSum, matrix[n-1][j]);
        }

        return minSum;
    }
}

Minimum Falling Path Sum in C++

class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) {
        int n = matrix.size();
        if (n == 0) {
            return 0;
        }

        // We can use the matrix itself as the DP table to save space.
        // matrix[i][j] will store the minimum falling path sum ending at (i, j).

        // Iterate from the second row to the end.
        for (int i = 1; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                // Find the minimum path sum from the previous row.
                // The previous cell can be (i-1, j-1), (i-1, j), or (i-1, j+1).
                
                // Start with the cell directly above.
                int min_prev = matrix[i-1][j];
                
                // Check the diagonally left cell.
                if (j > 0) {
                    min_prev = min(min_prev, matrix[i-1][j-1]);
                }
                
                // Check the diagonally right cell.
                if (j < n - 1) {
                    min_prev = min(min_prev, matrix[i-1][j+1]);
                }
                
                // Update the current cell's value with the minimum path sum.
                matrix[i][j] += min_prev;
            }
        }

        // The result is the minimum value in the last row.
        int result = matrix[n-1][0];
        for (int j = 1; j < n; ++j) {
            result = min(result, matrix[n-1][j]);
        }

        return result;
    }
};

Minimum Falling Path Sum in TypeScript

function minFallingPathSum(matrix: number[][]): number {
    const n = matrix.length;
    if (n === 0) {
        return 0;
    }

    // We use the matrix itself as the DP table to achieve O(1) space.
    // matrix[i][j] will store the minimum falling path sum ending at (i, j).

    // Iterate from the second row to the end.
    for (let i = 1; i < n; i++) {
        for (let j = 0; j < n; j++) {
            // Find the minimum path sum from the previous row.
            // The previous cell can be (i-1, j-1), (i-1, j), or (i-1, j+1).

            // Start with the cell directly above.
            let minPrev = matrix[i - 1][j];

            // Check the diagonally left cell.
            if (j > 0) {
                minPrev = Math.min(minPrev, matrix[i - 1][j - 1]);
            }

            // Check the diagonally right cell.
            if (j < n - 1) {
                minPrev = Math.min(minPrev, matrix[i - 1][j + 1]);
            }

            // Update the current cell's value with the minimum path sum.
            matrix[i][j] += minPrev;
        }
    }

    // The result is the minimum value in the last row.
    // Using spread operator with Math.min to find the minimum in the last row.
    return Math.min(...matrix[n - 1]);
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.