#64

Minimum Path Sum

Medium
ArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^(m+n))
O(m*n)
Space
O(m+n)
O(m*n)
💡

Intuition

Time O(m*n)Space O(m*n)

The optimal solution uses dynamic programming to build a table where each cell represents the minimum path sum to that cell. This approach avoids redundant calculations and efficiently finds the minimum path sum.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a 2D array 'dp' of the same size as the grid.
  2. 2Step 2: Initialize dp[0][0] with grid[0][0].
  3. 3Step 3: Fill the first row and first column of dp with cumulative sums.
  4. 4Step 4: For each cell in the grid, calculate dp[i][j] as the minimum of the sum from the top or left cell plus the current cell value.
  5. 5Step 5: Return the value in dp[m-1][n-1] as the result.
solution.py12 lines
1def minPathSum(grid):
2    m, n = len(grid), len(grid[0])
3    dp = [[0] * n for _ in range(m)]
4    dp[0][0] = grid[0][0]
5    for i in range(1, m):
6        dp[i][0] = dp[i-1][0] + grid[i][0]
7    for j in range(1, n):
8        dp[0][j] = dp[0][j-1] + grid[0][j]
9    for i in range(1, m):
10        for j in range(1, n):
11            dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
12    return dp[m-1][n-1]

Complexity note: The time complexity is O(m*n) because we iterate through each cell in the grid once. The space complexity is also O(m*n) due to the additional dp array used to store intermediate results.

  • 1Dynamic programming is a powerful technique for optimization problems.
  • 2Understanding how to build solutions incrementally can lead to efficient algorithms.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.