Skip to main content

Minimum Path Sum

LeetCode 64 | Difficulty: Medium​

Medium

Problem Description​

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`

Topics: Array, Dynamic Programming, Matrix


Approach​

Dynamic Programming​

Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.

When to use

Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).

Matrix​

Treat the matrix as a 2D grid. Common techniques: directional arrays (dx, dy) for movement, BFS/DFS for connected regions, in-place marking for visited cells, boundary traversal for spiral patterns.

When to use

Grid traversal, island problems, path finding, rotating/transforming matrices.


Solutions​

Solution 1: C# (Best: 208 ms)​

MetricValue
Runtime208 ms
MemoryN/A
Date2018-03-06
Solution
public class Solution {
public int MinPathSum(int[,] grid) {
int m = grid.GetLength(0);
int n = grid.GetLength(1);

int[,] dp = new int[m,n];
dp[0,0] = grid[0,0];
for (int i = 1; i < m; i++)
{
dp[i,0] = dp[i-1,0]+grid[i,0];
}
for (int j = 1; j < n; j++)
{
dp[0, j] = dp[0,j - 1] + grid[0,j];
}
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
{
dp[i,j] = grid[i,j] + Math.Min(dp[i-1,j],dp[i,j-1]);
}
}
return dp[m-1,n-1];
}
}

Complexity Analysis​

ApproachTimeSpace
DP (2D)$O(n Γ— m)$$O(n Γ— m)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
  • Consider if you can reduce space by only keeping the last row/few values.