Minimum path sum in grid

Dynamic Programming DP on grids Medium
  • This type of problem is a typical example of dynamic programming and is practically used in routing and navigation systems in maps
  • For instance, Google Maps or GPS systems finding the shortest or least congested path from one point to another uses similar concepts
  • The cells in the matrix can correspond to different routes, and the integer values can be considered as the cost, time or distance of traveling through that route

Given a 2d array called matrix consisting of integer values. Return the minimum path sum that can be obtained by starting at any cell in the first row and ending at any cell in the last row.


Movement is allowed only to the bottom, bottom-right, or bottom-left cell of the current cell.

Examples:

Input: matrix = [[1, 2, 10, 4], [100, 3, 2, 1], [1, 1, 20, 2], [1, 2, 2, 1]]

Output: 6

Explanation: One optimal route can be:-

Start at 1st cell of 1st row -> bottom-right -> bottom -> bottom-left.

Input: matrix = [[1, 4, 3, 1], [2, 3, -1, -1], [1, 1, -1, 8]]

Output: -1

Explanation: One optimal route can be:-

Start at 4th cell of 1st row -> bottom-left -> bottom.

Input: matrix = [[4, 3, 4], [4, 5, 1], [4, 6, 2], [4, 1, 4]]

Constraints

  • m == number of rows in matrix
  • n == number of columns in matrix
  • 1 <= n, m <= 100
  • -1000 <= matrix[i][j] <= 1000
  • The answer will not exceed 109

Hints

  • Let dp[i][j] be the minimum path sum to reach cell (i, j). The answer is the minimum value in the last row:min(dp[m−1][0],dp[m−1][1],...,dp[m−1][n−1])
  • "A recursive approach results in exponential time complexity (O(3^m)) due to overlapping subproblems. Using dynamic programming (O(m * n)), store results in a dp[][] table to avoid redundant calculations."

Company Tags

Pinterest Robinhood NVIDIA Goldman Sachs ARM Instacart Airbnb Philips Healthcare Johnson & Johnson Snowflake Cerner HashiCorp eBay Red Hat Etsy Reddit Intel Rakuten Teladoc Health Nutanix Seagate Technology PayPal Epic Systems Wayfair KPMG Google Microsoft Amazon Meta Apple Netflix Adobe