Skip to problem
←

Minimum Path Sum

Medium 0 attempts

Given a nonempty rectangular grid of nonnegative integers, find a path from the top-left cell to the bottom-right cell with the smallest sum of visited values.

Each move goes exactly one cell right or down. Diagonal, upward, and leftward moves are not allowed. Count both the starting and ending cells. Return the minimum sum, not the path itself. A one-cell grid returns that cell’s value.

In Example 1, moving right, right, down, down visits 1 → 3 → 1 → 1 → 1, totaling 7.

Function contract

Implement minPathSum(grid). Receive a nonempty rectangular matrix of nonnegative integers. You may modify grid while computing the answer.

Output: Return the minimum sum along a top-left to bottom-right path, including both endpoint values.

Example 1

Input
grid = [[1,3,1],[1,5,1],[4,2,1]]
Output
7

Example 2

Input
grid = [[5]]
Output
5
Visual Aid
Example 1: include both endpoints
Minimum path goes across the top row then down the right column, totaling seven131151421Right → right → down → down1 + 3 + 1 + 1 + 1 = 7Return 7

The five cells with bold borders form a minimum-cost path. Only rightward and downward moves are used.

Constraints
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 100

Dynamic Programming in the Input Grid

Process cells row by row. Overwrite each cell with the smallest path sum reaching it: its original cost plus the smaller of the already-computed top and left sums. The starting cell stays unchanged. Use Infinity for a missing neighbor so the first row and column can only extend their one available path.

The last cell then holds the answer. Reusing the input grid gives constant auxiliary space and is allowed by the contract.

javascript
function minPathSum(grid) {
  const m = grid.length, n = grid[0].length;
  for (let i = 0; i < m; i++)
    for (let j = 0; j < n; j++) {
      if (i === 0 && j === 0) continue;
      const top = i > 0 ? grid[i-1][j] : Infinity;
      const left = j > 0 ? grid[i][j-1] : Infinity;
      grid[i][j] += Math.min(top, left);
    }
  return grid[m-1][n-1];
}

Time: O(mn) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript