InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Unique Paths II

medium Original β†—
Solving tips
  • This is Unique Paths with an obstacle mask: keep dp[i][j] = dp[i-1][j] + dp[i][j-1] but force blocked cells to 0.
  • Do NOT initialize the whole first row/column to 1 as in Unique Paths β€” an obstacle casts a shadow, zeroing every cell after it; build base cells through the recurrence instead.
  • Seed dp[0][0]=1 only if the start cell is free, and remember the goal being blocked yields 0.
  • Target O(m*n) time, O(n) space with a rolling row; guard neighbor reads with i>0 / j>0 to avoid Python's negative-index wraparound.

Problem

A robot starts in the top-left cell of a grid and may move only right or down. The grid now contains obstacles: obstacleGrid[i][j] == 1 marks a blocked cell the robot cannot enter, and 0 marks a free cell. Count the number of distinct right/down paths from the top-left to the bottom-right cell. If the start or the goal is blocked, the answer is 0.

Examples

  • obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] β†’ 2 β€” the single obstacle in the center leaves exactly two routes (hug the top-right corner or the bottom-left corner).
  • obstacleGrid = [[0,1],[0,0]] β†’ 1 β€” the only route is down then right.
  • obstacleGrid = [[1,0]] β†’ 0 β€” the start cell itself is blocked.

Constraints

  • 1 <= m, n <= 100
  • Each cell is 0 (free) or 1 (obstacle).
  • The answer fits in a 32-bit signed integer.
  • As in Unique Paths, the path count can be huge, so an O(mΒ·n) DP is expected β€” enumeration is impossible.

Think about it first

Hint 1 This is Unique Paths with one extra rule: a blocked cell contributes zero paths. Start from the same recurrence and force `dp` to `0` wherever there is an obstacle.
Hint 2 The first row and first column are no longer all `1`. Once an obstacle appears in the top row, every cell after it in that row is unreachable β€” a single obstacle "casts a shadow" along the row (and likewise down the first column).
Hint 3 `dp[i][j] = 0` if `obstacleGrid[i][j] == 1`, else `dp[i-1][j] + dp[i][j-1]`. Seed `dp[0][0] = 1` only if the start is free. A single rolling array of length `n` works: zero out a slot when its cell is blocked.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.