Minimum Path Sum — LeetCode 64 Python Solution

MediumArrayDynamic ProgrammingMatrix
Problem
#64
Reading time
2 min

The problem

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time.

Example

Input
grid = [[1,3,1],[1,5,1],[4,2,1]]
Output
7
Explanation
Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Python solution

Python
class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        f = [[0] * n for _ in range(m)]
        f[0][0] = grid[0][0]
        for i in range(1, m):
            f[i][0] = f[i - 1][0] + grid[i][0]
        for j in range(1, n):
            f[0][j] = f[0][j - 1] + grid[0][j]
        for i in range(1, m):
            for j in range(1, n):
                f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]
        return f[-1][-1]

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 64. Minimum 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

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 64. Minimum Path Sum?
LeetCode 64. Minimum Path Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 64. Minimum Path Sum?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 64. Minimum Path Sum?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 64. Minimum Path Sum cover?
LeetCode 64. Minimum 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