SDE & MLE Prep

63. Unique Paths II

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]