Minimum Path Sum — LeetCode 64 Python Solution
- Problem
- #64
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(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.