Typorithm · medium

Minimum Path Sum

▷ Interactive algorithm labminimum-path-sum-dpdynamic-programminggridminimization
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Minimum Path Sum

0%

Dynamic Programming

Minimum Path Sum chooses the cheaper path to each grid cell from top or left.

Each cell has a path cost.

The transition reads top and left because moves are right/down.

A one-row dp array stores top and current-left costs.

Preparing algorithm lab…
01

State: minimum cost to current cell.

02

Invalid left edge uses Infinity.

03

Transition: cell + min(top, left).

04

Space O(cols).

function minPathSum(grid) {
  const rows = grid.length;
  const cols = grid[0].length;
  const dp = Array(cols).fill(Infinity);
  dp[0] = 0;

  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      dp[col] = grid[row][col] + Math.min(dp[col], col > 0 ? dp[col - 1] : Infinity);
    }
  }

  return dp[cols - 1];
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Blocked unknowns

Infinity prevents invalid directions from winning.

const dp = Array(cols).fill(Infinity)

2. Start before first cell

The first cell adds to zero cost.

dp[0] = 0

3. Min top/left

Current cost plus cheaper of top or left.

grid[row][col] + Math.min(dp[col], col > 0 ? dp[col - 1] : Infinity)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Minimum Path Sum: Visual Walkthrough & Practice · Typorithm | ApplyDjinn