63 - Unique Paths II
Difficulty: Medium | Pattern: Dynamic Programming (Grid) | Company tags: Amazon, Google, Microsoft
Problem Statement
You are given an m x n integer array grid. There is a robot initially located at the top-left corner (grid[0][0]). The robot tries to move to the bottom-right corner (grid[m-1][n-1]). The robot can only move either down or right at any point in time.
An obstacle and space are marked as 1 or 0 respectively in 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.
Example 1:
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2 (two paths avoid the center obstacle)
Example 2:
Input: obstacleGrid = [[0,1],[0,0]]
Output: 1
Approach: In-place DP — O(mn), O(1)
Key insight: dp[i][j] = number of ways to reach (i,j). If obstacle, 0. Otherwise dp[i][j] = dp[i-1][j] + dp[i][j-1]. Modify grid in place.
def uniquePathsWithObstacles(obstacleGrid: list[list[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
if obstacleGrid[0][0] == 1 or obstacleGrid[m-1][n-1] == 1:
return 0
obstacleGrid[0][0] = 1
for i in range(1, m):
obstacleGrid[i][0] = 0 if obstacleGrid[i][0] == 1 else obstacleGrid[i-1][0]
for j in range(1, n):
obstacleGrid[0][j] = 0 if obstacleGrid[0][j] == 1 else obstacleGrid[0][j-1]
for i in range(1, m):
for j in range(1, n):
if obstacleGrid[i][j] == 1:
obstacleGrid[i][j] = 0
else:
obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]
return obstacleGrid[m-1][n-1]
Dry Run
[[0,0,0],
[0,1,0],
[0,0,0]]
After filling:
[[1,1,1],
[1,0,1],
[1,1,2]]
Answer: 2 ✓
Edge Cases
- Start
(0,0)is obstacle → return 0 - End is obstacle → return 0
- Obstacle in first row/column blocks all paths beyond it → those cells become 0
- 1x1 grid with no obstacle → 1
Complexity
- Time: O(m x n)
- Space: O(1) (in-place)