MediumNeetCode150ArrayDynamic ProgrammingMatrix

Unique Paths II

Count paths with obstacles.

Examples

Input
obstacleGrid = [[0,1],[0,0]]
Output
1

One path avoiding obstacle.

Constraints

  • m == obstacleGrid.length
  • n == obstacleGrid[0].length
  • 1 <= m,n <= 100

Approaches

DFS with obstacle check.

CodeT: O(2^(m+n)) | S: O(m+n) stack

dp[i][j] = 0 if obstacle.

CodeT: O(m*n) | S: O(m*n)

Modify grid directly.

CodeT: O(m*n) | S: O(1)

Complexity Comparison

Recursion
T: O(2^(m+n))S: O(m+n) stack

DFS with obstacle check.

DP 2D
T: O(m*n)S: O(m*n)

dp[i][j] = 0 if obstacle.

DP In Place
T: O(m*n)S: O(1)

Modify grid directly.

Common Mistakes

Not handling start/end obstacles

Wrong initialization

Off-by-one

Try It Yourself

Copy the optimal solution and run it in our compiler.

Open in Compiler