Minimum Path Sum

Medium Dynamic Programming 2D DP Original on LeetCode

Reported atPaytmDream11

Minimum Path Sum is a medium dynamic programming problem solved with the 2d dp pattern. The best approach, optimal (one row), runs in O(m · n) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from recursion up.

Problem

Find a path from the top-left to the bottom-right of a grid of non-negative numbers, moving only right or down, that minimises the sum of the numbers along it.

Examples

Example 1

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

Example 2

Input
grid = [[1,2,3],[4,5,6]]
Output
12

Constraints

  • 1 <= m, n <= 200; values 0 to 200.
  • Move only right or down.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
RecursionO(2^(m + n))O(m + n)
Tabulation (2D table)O(m · n)O(m · n)
Optimal (one row)O(m · n)O(n)

1Recursion

TimeO(2^(m + n))
SpaceO(m + n)

The cheapest path into (i, j) comes from above or from the left.

  1. cost(0, 0) = grid[0][0]; out of bounds = infinity.
  2. cost(i, j) = grid[i][j] + min(cost(i - 1, j), cost(i, j - 1)).
class Solution {
    public int minPathSum(int[][] grid) {
        return cost(grid, grid.length - 1, grid[0].length - 1);
    }

    private int cost(int[][] g, int i, int j) {
        if (i < 0 || j < 0) return Integer.MAX_VALUE;
        if (i == 0 && j == 0) return g[0][0];
        return g[i][j] + Math.min(cost(g, i - 1, j), cost(g, i, j - 1));
    }
}

2Tabulation (2D table)

TimeO(m · n)
SpaceO(m · n)

Fill the table row by row. The first row and first column each have only one way in.

  1. dp[0][0] = grid[0][0]; fill the first row and column with running sums.
  2. dp[i][j] = grid[i][j] + min(up, left).
class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) dp[i][j] = grid[0][0];
                else if (i == 0) dp[i][j] = dp[i][j - 1] + grid[i][j];
                else if (j == 0) dp[i][j] = dp[i - 1][j] + grid[i][j];
                else dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
            }
        return dp[m - 1][n - 1];
    }
}

3Optimal (one row)

TimeO(m · n)
SpaceO(n)

Keep a single row. Before updating, dp[j] still holds the value from the row above, and dp[j - 1] already holds the new value to the left.

  1. dp[j] = grid[i][j] + min(dp[j] (up), dp[j - 1] (left)).
class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int[] dp = new int[n];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                dp[j] = grid[i][j] + (j == 0 ? dp[0] : Math.min(dp[j], dp[j - 1]));
        return dp[n - 1];
    }
}

Edge cases to test

  • Single row or single column

Hints

Hint 1

dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]).

FAQ

What is the best time complexity for Minimum Path Sum?

Optimal (one row) runs in O(m · n) time and O(n) extra space.

Which pattern does Minimum Path Sum use?

It is a dynamic programming problem that uses the 2d dp pattern. Other problems with the same pattern: Unique Paths, Unique Paths II, Dungeon Game.

Is there a brute force solution for Minimum Path Sum?

Yes. Recursion takes O(2^(m + n)) time and O(m + n) space. The cheapest path into (i, j) comes from above or from the left.

Which edge cases should I test for Minimum Path Sum?

Single row or single column.