63. Unique Paths II
Asked at 11Bloomberg50Amazon41Google31Microsoft23Meta22IMC74Agoda64Nvidia60Flipkart43TikTok35Goldman Sachs21
Problem
Same as Unique Paths (moves right or down only), but cells with 1 in obstacleGrid are blocked. Count the paths from the top-left to the bottom-right.
Example: [[0,0,0],[0,1,0],[0,0,0]] → 2
Same recurrence, but obstacle cells contribute 0.
Complexity: O(m·n) time, O(n) space.
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
n = len(obstacleGrid[0])
row = [0] * n
row[0] = 1
for r in obstacleGrid:
for c in range(n):
if r[c]:
row[c] = 0
elif c:
row[c] += row[c - 1]
return row[-1]
assert Solution().uniquePathsWithObstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == 2
assert Solution().uniquePathsWithObstacles([[0, 1], [0, 0]]) == 1
class Solution {
public int uniquePathsWithObstacles(int[][] grid) {
int n = grid[0].length;
int[] row = new int[n];
row[0] = 1;
for (int[] r : grid)
for (int c = 0; c < n; c++) {
if (r[c] == 1) row[c] = 0;
else if (c > 0) row[c] += row[c - 1];
}
return row[n - 1];
}
}
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
n := len(obstacleGrid[0])
row := make([]int, n)
row[0] = 1
for _, r := range obstacleGrid {
for c := 0; c < n; c++ {
if r[c] == 1 {
row[c] = 0
} else if c > 0 {
row[c] += row[c-1]
}
}
}
return row[n-1]
}