InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Minimum Path Sum

medium Original ↗ 00:00

Problem

Given an m x n grid filled with non-negative integers, find a path from the top-left cell to the bottom-right cell that minimizes the sum of the numbers along it. You may only move right or down at each step.

Return that minimum sum.

Examples

  • [[1, 3, 1], [1, 5, 1], [4, 2, 1]]7 — the path 1 → 3 → 1 → 1 → 1 (right, right, down, down) sums to 7.
  • [[1, 2, 3], [4, 5, 6]]121 → 2 → 3 → 6 sums to 12; going down early costs more.
  • [[5]]5 — a single cell; the path is just that cell.

Constraints

  • m == grid.length, n == grid[0].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200

Enumerating all right/down paths is exponential (there are C(m+n, m) of them); the expected solution is O(m × n).

Think about it first

Hint 1 Every cell is reached from either the cell directly above or the cell directly to its left — those are the only two moves. So the cheapest way to reach a cell is its own value plus the cheaper of those two predecessors.
Hint 2 Let `dp[i][j]` be the minimum path sum to reach cell `(i, j)` from the top-left. That's a 2-D table filled top-to-bottom, left-to-right.
Hint 3 `dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1])`. The first row and first column have only one predecessor each (a running prefix sum). The answer is `dp[m-1][n-1]`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug