AlgoInsight

DSA problem

Minimum Path Sum

Medium2D Grid DPPattern: 2D Grid DPtop75AmazonMicrosoftGoogleGoldman SachsApple

Given an m x n grid of non-negative integers, find a path from the top-left corner to the bottom-right corner that minimizes the sum of the numbers along the path. You can only move either down or right at any step.

This problem is the additive cousin of "Unique Paths". Instead of counting paths we minimize their cost, but the underlying structure is identical: any optimal path arriving at cell (i, j) must come from either (i - 1, j) or (i, j - 1). So the recurrence is dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]), with the first row and first column filled by prefix sums (they have only one predecessor each).

A brute-force search would explore every monotone path, costing O(C(m + n - 2, m - 1)) operations — exponential in the grid dimensions. Memoization shrinks that to O(m * n) by caching the minimum cost from each cell to the destination. Bottom-up tabulation does the same work iteratively with a clean two-pass fill.

The optimal space-optimized version uses a single rolling row dp of length n. Initialize it with the prefix sums of the first grid row. For each subsequent row, set dp[0] += grid[i][0] (only one predecessor) and then for j >= 1 do dp[j] = grid[i][j] + min(dp[j], dp[j - 1]). The "old" dp[j] represents the cost from above; the "new" dp[j - 1] represents the cost from the left. This is O(m * n) time and O(n) space.

Examples

Example 1
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: The path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum (1 + 3 + 1 + 1 + 1 = 7).
Example 2
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Explanation: The path 1 -> 2 -> 3 -> 6 totals 12, which is optimal for a 2x3 grid.
Example 3
Input: grid = [[5]]
Output: 5
Explanation: The single cell is both the start and the destination.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraydynamic-programmingmatrix

Browse all DSA problems