Minimum Path Sum in Grid
Master this topic with zero to advance depth.
Minimum Path Sum in Grid
Given a m x n grid filled with non-negative numbers, find a path from top-left to bottom-right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Visual Representation
Grid:
[1, 3, 1]
[1, 5, 1]
[4, 2, 1]
Paths:
1-3-1-1-1 = 7 (Min)
1-1-5-2-1 = 10
1-1-4-2-1 = 9Examples
Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Level I: Dynamic Programming (2D)
Intuition
The minimum sum to reach cell (i, j) is the value of the current cell plus the minimum of the paths reaching from above (i-1, j) or from the left (i, j-1).
Thought Process
dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).- Edges: For the first row, you can only come from the left. For the first column, you can only come from above.
- Base Case:
dp[0][0] = grid[0][0].
Detailed Dry Run
grid = [[1, 3], [1, 5]]
| Cell | Calculation | Sum |
|---|---|---|
| (0, 0) | Base | 1 |
| (0, 1) | 1 + grid[0][1] = 1+3 | 4 |
| (1, 0) | 1 + grid[1][0] = 1+1 | 2 |
| (1, 1) | 5 + min(dp[0][1], dp[1][0]) = 5 + min(4, 2) | 7 |
Level II: Memoization (Top-Down Recursion)
Intuition
The recursive brute force for grid path counting has overlapping subproblems. We cache each (i, j) state so we never recompute it.
Visual
Memo Grid (m=3, n=3):
| 0 | 1 | 1 |
| 1 | 2 | ? | <- memo[1][2] reused by (2,2)
| 1 | ? | ? |Detailed Dry Run
m=3, n=3. memo[2][2] = memo[1][2] + memo[2][1]. Both sub-calls are cached after first computation.
⚠️ Common Pitfalls & Tips
Recursion adds O(M+N) stack overhead compared to the iterative DP. For very large grids, prefer the iterative approach to avoid stack overflow.
Level III: Space Optimized (1D)
Intuition
To compute dp[i][j], we only need the value above it (previous row) and the value to its left (current row). We can use a single array of size n.
Logic Steps
- Initialize
rowarray of sizenwithInfinity. - Set
row[0] = 0(starting point for accumulation). - For each
i(row):row[0] += grid[i][0]- For each
j(col from 1 ton-1):row[j] = grid[i][j] + min(row[j], row[j-1]).
- Return
row[n-1].
Detailed Dry Run
grid = [[1, 3], [1, 5]]
| Row | row array calculation | State |
|---|---|---|
| 0 | [1, 1+3=4] | [1, 4] |
| 1 | [1+1=2, 5+min(2, 4)=7] | [2, 7] |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.