Taro Logo

Minimum Path Sum

#47 Most AskedMedium
0 views
Topics:
ArraysDynamic Programming

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.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200

Solution


Clarifying Questions

When 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:

  1. What are the constraints on the dimensions of the grid ($m$ and $n$), and can the grid be empty or jagged (non-rectangular)?
  2. Are the numbers in the grid guaranteed to be strictly non-negative integers, or could we encounter floating-point numbers or negative values?
  3. Should we modify the input grid in-place to save space, or is it expected that we keep the original grid unmodified?
  4. What should be returned if the grid contains a single cell? Should it just return the value of that single cell?
  5. Is it guaranteed that a valid path always exists from the top-left to the bottom-right corner?

Brute Force Solution

Approach

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:

  1. Begin at the starting square in the top-left corner and note its number.
  2. Look at all the possible directions you can move, which are either down or to the right.
  3. Choose one direction and step to the next square, adding its number to your running total.
  4. Keep moving down and right, step by step, until you eventually reach the bottom-right corner.
  5. Once you finally arrive at the destination, write down the grand total of all the numbers you stepped on.
  6. Go all the way back to the start and trace out a completely different path of downs and rights, and calculate that total too.
  7. Repeat this exhausting process for every single unique combination of paths through the grid.
  8. Finally, compare all the totals you collected and pick the smallest one as your answer.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(2^(m+n)) – The brute force strategy explores every possible path by branching into two choices, moving either down or right, at every single cell until reaching the bottom-right corner. In a grid with m rows and n columns, the total number of steps to reach the destination is roughly (m + n - 2), and at each step, the algorithm makes a binary choice. This recursive exploration results in an exponential number of total operations proportional to 2 to the power of (m + n), which simplifies to O(2^(m+n)) when treating the grid dimensions as the input size.
Space Complexity
O(1) – The brute force approach as described only requires a few primitive variables to track the current running total and the final minimum sum, operating entirely in place without creating any auxiliary data structures. As the grid dimensions grow, the extra memory required remains completely constant because no recursive stack frames or temporary lists are utilized to store intermediate path results. Therefore, the auxiliary space complexity is constant, which simplifies to Big O of 1.

Optimal Solution

Approach

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:

  1. Picture a grid of numbers where you need to travel from the top left corner to the bottom right corner, only moving down or to the right, while keeping the sum of the numbers you pass over as small as possible.
  2. Start at the very beginning spot and record its value as the cheapest current total to get there.
  3. Look at the spots along the very top edge. Since you can only arrive at these by coming straight from the left, calculate the running total by adding the current spot to the total of the spot immediately before it.
  4. Do the same for the spots along the far left edge, but this time calculate the running total by adding the current spot to the total of the spot immediately above it.
  5. For every other spot in the middle of the grid, look at the neighbor directly above you and the neighbor directly to your left.
  6. Compare the running totals of those two neighbors and pick the smaller one.
  7. Add that smaller neighbor total to the value of your current spot to get the cheapest possible running total for where you are standing.
  8. Continue this process row by row until you reach the final bottom right spot, which will automatically hold the absolute minimum path sum.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(m * n) – To find the minimum path sum, we iterate through every cell in the grid of size m rows by n columns. For each cell in the middle of the grid, we perform a constant number of operations by comparing the values from the top and left neighbors. This requires a nested loop structure where the outer loop runs across the rows and the inner loop runs across the columns. Ultimately, the total operations approximate m * n steps, which simplifies to the Big O time complexity of O(m * n).
Space Complexity
O(1) – The algorithm modifies the input grid directly in place without utilizing any auxiliary data structures, temporary lists, or recursion stack frames. As the grid dimensions grow, the extra memory required remains constant because only a few primitive variables are used to keep track of the iteration indices. Therefore, the auxiliary space complexity is strictly constant relative to the input size.

Edge Cases

Null or completely empty grid input
How to Handle:
Check for null or zero-row inputs at the start and return zero immediately.
Grid with dimensions of 1x1
How to Handle:
Return the single value in the grid since no movement is required.
Grid with only a single row (1xn)
How to Handle:
Initialize the DP state by taking a running cumulative sum horizontally across that single row.
Grid with only a single column (mx1)
How to Handle:
Initialize the DP state by taking a running cumulative sum vertically down that single column.
Grid containing zeros alongside positive numbers
How to Handle:
Addition naturally preserves zero values so path sums remain correct without special conditional branches.
Maximum grid dimensions approaching constraint limits
How to Handle:
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
How to Handle:
Use standard 64-bit integer types if the accumulated path sum exceeds standard 32-bit integer limits.
All grid cells containing identical values
How to Handle:
The recurrence relation evaluates all paths equally and correctly returns the mathematically minimal accumulated sum.
0/257 completed