Minimum Path Sum

MediumDynamic Programming · 2D Grid🧩 Grid DPLeetCode #64 ↗Updated

Problem

You are given an m × n grid of non-negative integers. Travel from the top-left cell to the bottom-right cell moving only right or down, and return the smallest possible sum of the values on the cells you visit (both ends included).
Input[[1,3,1],[1,5,1],[4,2,1]]Output7 (1→3→1→1→1)
Input[[1,2,3],[4,5,6]]Output12

1 ≤ m, n ≤ 200  ·  0 ≤ grid[i][j] ≤ 200

Try it yourself

Java
class Solution {
    public int minPathSum(int[][] grid) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The cheapest way into cell (i, j) must come from the cheaper of its top or left neighbour, so best(i,j) = grid[i][j] + min(best(i-1,j), best(i,j-1)). Fill row by row.
PatternGrid DP

Instinct Grid moves that never loop back (right/down, row to row) plus "count or optimise the paths" - build dp[r][c] from the cells that can step in.

Memory hack Every cell asks its parents - a cell's answer comes only from the neighbours that can move into it, so fill cells in the order they arrive.

Open the Grid DP guide →

Approaches

Brute ForceRecursion (Min of Top / Left)

Time O(2m+n)Space O(m + n)

minSum(i, j) = cheapest path from (0,0) to (i,j). On the first row or column there is only one way in; elsewhere take the cheaper of the top and left sub-answers. Overlapping sub-problems are recomputed again and again.

Java
public int minPathSum(int[][] grid) {
    return minSum(grid, grid.length - 1, grid[0].length - 1);
}
private int minSum(int[][] grid, int i, int j) {
    if (i == 0 && j == 0) return grid[0][0];
    if (i == 0) return grid[i][j] + minSum(grid, i, j - 1);   // only from left
    if (j == 0) return grid[i][j] + minSum(grid, i - 1, j);   // only from top
    return grid[i][j] + Math.min(minSum(grid, i - 1, j), minSum(grid, i, j - 1));
}

Captures the recurrence, but exponential — useless for 200×200.

At a glance

LevelApproachTimeSpace
Brute ForceRecursion (Min of Top / Left)O(2m+n)O(m + n)
BetterBottom-Up 2D DP TableO(m · n)O(m · n)
OptimalIn-Place DP on the GridO(m · n)O(1)
Common pitfalls
  • Treating the first row/column like inner cells — out-of-bounds or wrong mins.
  • Using Integer.MAX_VALUE as a sentinel and adding to it — overflow.
  • Mutating the grid without saying so — callers may reuse it.
Interview tips
  • Explain why greedy (cheapest next step) fails: a cheap step can lead to an expensive area.
  • Ask whether modifying the input is allowed before choosing in-place.
  • Same template as Unique Paths: replace + with min + cell cost.
Pattern
2D grid path DP → optimise a cost over right/down paths; state = cell, combine top & left.
My notes saved in this browser