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
๐ค Output