Skip to content
DSA Patterns
Menu
Language
Two-Dimensional DPLC #643 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Minimum Path Sum

Problem (restated)

m×n grid of non-negatives. Path from top-left to bottom-right (right/down only). Minimize sum.

Intuition

dp[i][j] = grid + min(from top, from left). Fill first row/col then rest.

Approaches

Grid DP in-place

Unverified
Time O(mn)Space O(1) extra

Idea. can mutate grid: grid[i][j] += min(up, left).

Walkthrough. [[1,3,1],[1,5,1],[4,2,1]] → 7 (1→3→1→1→1).

Trade-offs. Same family as unique paths; add cost.

Solution
export function minPathSum(grid: number[][]): number {
  const m = grid.length, n = grid[0]!.length;
  for (let i = 1; i < m; i++) grid[i]![0]! += grid[i - 1]![0]!;
  for (let j = 1; j < n; j++) grid[0]![j]! += grid[0]![j - 1]!;
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      grid[i]![j]! += Math.min(grid[i - 1]![j]!, grid[i]![j - 1]!);
    }
  }
  return grid[m - 1]![n - 1]!;
}
export function minPathSum(grid: number[][]): number {
  const m = grid.length, n = grid[0]!.length;
  for (let i = 1; i < m; i++) grid[i]![0]! += grid[i - 1]![0]!;
  for (let j = 1; j < n; j++) grid[0]![j]! += grid[0]![j - 1]!;
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      grid[i]![j]! += Math.min(grid[i - 1]![j]!, grid[i]![j - 1]!);
    }
  }
  return grid[m - 1]![n - 1]!;
}

Template connection

In-place grid DP. grid[i][j] adds min(up, left). The first row and the first column each have a single predecessor.

Reflection

  • Add the cell to min(above, left). The first row accumulates only from the left. The first column accumulates only from above.
  • Writing into the grid erases the input. Copy the grid when the caller still needs the original numbers.
  • One cell is itself. Values are non-negative. A single row is only horizontal.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Min path sum. Grid [[1,3,1],[1,5,1],[4,2,1]]. Right or down only.

1
3
1
1
5
1
4
2
1

dp[r][c] = grid + min(up, left)

Key:CurrentActive rangeMatchSettledEliminated