MEDIUM Dynamic Programming 2D
63. Unique Paths II
๐ Problem
You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. An obstacle and space is marked as 1 and 0 respectively in the grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner.
๐ง 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 where dp[i][j] represents number of ways to reach cell (i,j)
- โ If cell is obstacle, dp[i][j] = 0
- โ Otherwise, dp[i][j] = dp[i-1][j] + dp[i][j-1]
- โ Time: O(m * n), Space: O(m * n) or O(n) optimized
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse DP where dp[i][j] represents number of ways to reach cell (i,j)
- โขIf cell is obstacle, dp[i][j] = 0
- โขOtherwise, dp[i][j] = dp[i-1][j] + dp[i][j-1]
Common Pitfalls
- โขTime: O(m * n), Space: O(m * n) or O(n) optimized
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
uniquePathsWithObstacles([[0,0,0],[0,1,0],[0,0,0]]); Expected:
2 Test Case 2
Not run Input:
uniquePathsWithObstacles([[0,1],[0,0]]); Expected:
1 Test Case 3
Not run Input:
uniquePathsWithObstacles([[0,0]]); Expected:
1 ๐ Code Editor
๐ค Output