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 1:
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.
Example 2:
Input: grid = [[1,2,3],[4,5,6]] Output: 12
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 2000 <= grid[i][j] <= 200When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are standing at the top-left corner of a grid of numbers and need to find a path to the bottom-right corner while keeping the sum of the numbers as small as possible. The brute force approach works by stubbornly walking every single possible path from start to finish, adding up the numbers along the way.
Here's how the algorithm would work step-by-step:
class Solution:
def minPathSum(self, grid: list[list[int]]) -> int:
row_count = len(grid)
col_count = len(grid[0])
def explore_paths(current_row, current_col):
# Base case: if we reach the bottom-right corner, return its value as the path sum
if current_row == row_count - 1 and current_col == col_count - 1:
return grid[current_row][current_col]
# If we go past the bottom boundary, return infinity so this path is ignored
if current_row >= row_count:
return float('inf')
# If we go past the right boundary, return infinity so this path is ignored
if current_col >= col_count:
return float('inf')
# Explore both available moves and pick the one that yields the minimum sum
move_down_sum = explore_paths(current_row + 1, current_col)
move_right_sum = explore_paths(current_row, current_col + 1)
return grid[current_row][current_col] + min(move_down_sum, move_right_sum)
return explore_paths(0, 0)Instead of checking every single possible route through the grid, the optimal approach builds up the answer step by step. It figures out the cheapest way to reach every single spot by looking at the best choices made right before it.
Here's how the algorithm would work step-by-step:
def min_path_sum(grid_matrix): row_count = len(grid_matrix) column_count = len(grid_matrix[0]) # Top edge can only be reached from the left, so accumulate horizontally. for column_index in range(1, column_count): grid_matrix[0][column_index] += grid_matrix[0][column_index - 1] # Left edge can only be reached from above, so accumulate vertically. for row_index in range(1, row_count): grid_matrix[row_index][0] += grid_matrix[row_index - 1][0] # Interior cells take the minimum path from either the top or left neighbor. for row_index in range(1, row_count): for column_index in range(1, column_count): minimum_incoming_path = min(grid_matrix[row_index - 1][column_index], grid_matrix[row_index][column_index - 1]) grid_matrix[row_index][column_index] += minimum_incoming_path # The bottom-right corner holds the accumulated minimum path sum for the grid. return grid_matrix[row_count - 1][column_count - 1]| Case | How to Handle |
|---|---|
| Null or completely empty grid input | Check for null or zero-row inputs at the start and return zero immediately. |
| Grid with dimensions of 1x1 | Return the single value in the grid since no movement is required. |
| Grid with only a single row (1xn) | Initialize the DP state by taking a running cumulative sum horizontally across that single row. |
| Grid with only a single column (mx1) | Initialize the DP state by taking a running cumulative sum vertically down that single column. |
| Grid containing zeros alongside positive numbers | Addition naturally preserves zero values so path sums remain correct without special conditional branches. |
| Maximum grid dimensions approaching constraint limits | Use an in-place DP approach or a single-row rolling array to stay within optimal space complexity limits. |
| Extremely large numerical cell values leading to sum overflow | Use standard 64-bit integer types if the accumulated path sum exceeds standard 32-bit integer limits. |
| All grid cells containing identical values | The recurrence relation evaluates all paths equally and correctly returns the mathematically minimal accumulated sum. |