Minimum Path Sum in Python

The minimum path sum problem involves finding a path from the top-left corner to the bottom-right corner of a matrix that minimizes the sum of all numbers along the path. You can only move down or right at any point.

Problem Example

Given this matrix:

1 3 1
1 5 1
4 2 1

The optimal path is: 1 ? 3 ? 1 ? 1 ? 1, giving a minimum sum of 7.

Algorithm Steps

The dynamic programming approach works as follows:

  • Fill the bottom row: each cell adds the value from its right neighbor
  • Fill the rightmost column: each cell adds the value from its bottom neighbor
  • For remaining cells: add the minimum of right or bottom neighbor
  • Return the top-left cell value

Implementation

class Solution:
    def minPathSum(self, grid):
        rows = len(grid)
        cols = len(grid[0])
        
        # Fill bottom row (can only move right)
        for j in range(cols - 2, -1, -1):
            grid[rows - 1][j] += grid[rows - 1][j + 1]
        
        # Fill rightmost column (can only move down)
        for i in range(rows - 2, -1, -1):
            grid[i][cols - 1] += grid[i + 1][cols - 1]
        
        # Fill remaining cells (choose minimum path)
        for i in range(rows - 2, -1, -1):
            for j in range(cols - 2, -1, -1):
                grid[i][j] += min(grid[i][j + 1], grid[i + 1][j])
        
        return grid[0][0]

# Test the solution
solution = Solution()
matrix = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
result = solution.minPathSum(matrix)
print("Minimum path sum:", result)
Minimum path sum: 7

Step-by-Step Visualization

Let's trace through the algorithm:

# Original matrix
matrix = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
print("Original matrix:")
for row in matrix:
    print(row)

# After processing
solution = Solution()
result = solution.minPathSum([row[:] for row in matrix])  # Copy to avoid modifying original

print("\nMinimum path sum:", result)
print("Path: 1 ? 3 ? 1 ? 1 ? 1")
Original matrix:
[1, 3, 1]
[1, 5, 1]
[4, 2, 1]

Minimum path sum: 7
Path: 1 ? 3 ? 1 ? 1 ? 1

Time and Space Complexity

Complexity Value Explanation
Time O(m × n) Visit each cell once
Space O(1) Modifies input matrix in-place

Conclusion

The minimum path sum problem is solved efficiently using dynamic programming by building the solution from bottom-right to top-left. Each cell stores the minimum cost to reach the destination from that position.

Updated on: 2026-03-25T08:28:04+05:30

842 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements