MEDIUM 2-D Dynamic Programming

64. Minimum Path Sum

๐Ÿ“– Problem

Given a m x n grid filled with non-negative numbers, find a path from top left corner to bottom right corner which minimizes the sum of all numbers along its path.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขArray DP table updates
  • โ€ขState transition thinking
  • โ€ขBase case initialization

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Dynamic Programming reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use dp[i][j] = min path sum to reach cell (i, j)
  • โ†’ Base case: dp[0][0] = grid[0][0]
  • โ†’ For each cell: dp[i][j] = min(from above + left, from left + grid[i][j])
  • โ†’ Return dp[m-1][n-1]
  • โ†’ Time: O(m * n), Space: O(m * n) or O(n) optimized

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse dp[i][j] = min path sum to reach cell (i, j)
  • โ€ขBase case: dp[0][0] = grid[0][0]
  • โ€ขFor each cell: dp[i][j] = min(from above + left, from left + grid[i][j])

Common Pitfalls

  • โ€ขReturn dp[m-1][n-1]
  • โ€ขTime: O(m * n), Space: O(m * n) or O(n) optimized

๐Ÿงช Test Cases

Test Case 1
Not run
Input:
minPathSum([[1,3,1],[1,5,1],[4,2,1],[5,3,1],[2,3,1],[4,2,1]]);
Expected:
20
Test Case 2
Not run
Input:
minPathSum([[1,2,3],[4,5,6]]);
Expected:
16
Test Case 3
Not run
Input:
minPathSum(grid: number[][]);
Expected:
Computed from hidden reference

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit