Skip to content
Problem 64 · LeetCode 64(opens in a new tab)

Minimum Path Sum

MediumDynamic programming

You are given an m × n grid of non-negative whole numbers. Start in the top-left cell and walk to the bottom-right cell, moving only down or right one cell at a time.

The cost of a walk is the sum of every cell it visits, both ends included. Return the smallest possible cost.

Example 1

Input:  grid = [[2, 4, 1],
                [3, 8, 2],
                [6, 1, 5]]
Output: 14
Why:    2 → 4 → 1 → 2 → 5
2 more examples and the constraints

Example 2

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

Example 3

Input:  grid = [[3, 0, 4]]
Output: 7
Why:    one row: the only walk is straight across

Constraints

  • 1 ≤ m, n ≤ 200
  • 0 ≤ grid[r][c] ≤ 200

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion with memoO(m·n)
  2. DP table, row by rowO(m·n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 200 × 200 gridVerdict
Recursion with memoO(m·n)
Passes; call overhead and deep stack
DP table, row by rowO(m·n)
Best; simple loops

m = rows, n = columns. Without the memo, plain recursion is exponential.

Edge cases to test

  • One cell. [[5]] costs 5: the start is also the end.
  • One row or one column. There is only one walk, so the answer is the sum of the line.
  • Zeros. Cells of 0 are allowed; a grid of zeros costs 0.
  • Cheap detour. The best walk may go far down first, then right, even when the first step down costs more.

Common mistakes

  • Forgetting the top row and left column have only one neighbour, and reading outside the table.
  • Choosing the cheaper next cell greedily at each step; a cheap step now can lead into an expensive region.
  • Leaving out the start or the end cell from the sum.

How to talk through it

  1. 1Clarify. Only down and right? Are values non-negative? Do both corner cells count?
  2. 2Show greedy fails. Picking the cheaper neighbour each step can miss the best walk; a small grid shows it.
  3. 3State the recurrence. dp[r][c] = grid[r][c] + min(dp[r − 1][c], dp[r][c − 1]), with one-sided edges.
  4. 4Code the table. Fill row by row; mention the one-row version for O(n) space.
  5. 5Test out loud. Run a single cell, a single row and Example 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?