Unique Paths II (LeetCode 63): Solution and Explanation

Medium
Array
Dynamic Programming
Matrix

A robot moves only right or down across a grid from the top-left to the bottom-right corner. Some cells are obstacles it cannot enter. Count how many distinct paths reach the goal.

Intuition

Look at the last move of any path into a free cell. It came either from the cell directly above or from the cell directly to the left, and those two groups of paths never overlap. So the number of paths into a cell is the sum of the paths into those two neighbors.

Obstacles fit into the same rule with one change: no path can end on an obstacle, so its count is 0. That 0 then flows into its right and lower neighbors automatically, which is exactly how an obstacle cuts off routes.

Filling the grid row by row, each cell only looks at the row above and the cell to its left. That means one array of length n is enough. While processing column c, dp[c] still holds the count from the row above and dp[c - 1] has already been updated for the current row, so dp[c] += dp[c - 1] performs the whole recurrence in place.

Approach: Rolling 1-D dynamic programming

  1. Create dp of length n filled with 0 and set dp[0] = 1, the single way to stand on the start.
  2. For each row, scan columns c from 0 to n - 1.
  3. If the cell is an obstacle, set dp[c] = 0.
  4. Otherwise, if c > 0, add the left neighbor: dp[c] += dp[c - 1]. In column 0 the value from above is simply kept.
  5. After the last row, return dp[n - 1].

Step-by-step example

obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
  1. Start with dp = [1, 0, 0].
  2. Row 0: column 0 keeps 1, column 1 becomes 0 + 1 = 1, column 2 becomes 0 + 1 = 1. dp = [1, 1, 1].
  3. Row 1: column 0 keeps 1. Column 1 is the obstacle, so dp[1] = 0. Column 2 becomes 1 + 0 = 1. dp = [1, 0, 1].
  4. Row 2: column 0 keeps 1. Column 1 becomes 0 + 1 = 1. Column 2 becomes 1 + 1 = 2. dp = [1, 1, 2].
  5. The bottom-right count is dp[2] = 2.

Code: Python, Java, C++

1class Solution:
2    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
3        n = len(obstacleGrid[0])
4        dp = [0] * n
5        dp[0] = 1
6        for row in obstacleGrid:
7            for c in range(n):
8                if row[c] == 1:
9                    dp[c] = 0
10                elif c > 0:
11                    dp[c] += dp[c - 1]
12        return dp[n - 1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Every cell is visited once and does constant work.

Space

O(n)

Only one row of counts is stored, no matter how many rows the grid has.

Other approaches

Full 2-D DP table (time O(m * n), space O(m * n))

Store a count for every cell in an m x n table and fill it with the same above-plus-left rule. It is easier to print and debug, at the cost of O(m * n) memory.

Memoized DFS from the goal (time O(m * n), space O(m * n))

Recursively count paths into (r, c) as paths into (r - 1, c) plus (r, c - 1), caching each result. Same work, but recursion depth reaches m + n and the overhead is higher.

Common mistakes

  • Initializing the whole first row and first column to 1 as in Unique Paths I. An obstacle in the first row blocks every cell to its right, and one in the first column blocks every cell below it.
  • Forgetting that the start or the goal itself can be an obstacle, in which case the answer is 0.
  • Using a 32-bit int for intermediate counts in languages where overflow wraps silently. Cells that cannot reach the goal can still hold large counts.
  • Updating dp[c - 1] from the wrong row. Scan columns left to right so the left neighbor is already the current row's value.

Frequently asked questions

Why does setting an obstacle to 0 handle everything?

Its right and lower neighbors add its count into theirs. A 0 contributes nothing, which is the same as saying no path goes through it.

Why is one array enough?

Each cell needs only the cell above and the cell to the left. Before you overwrite dp[c] it still holds the value from the row above, and dp[c - 1] was just written for the current row.

Can I use the combinatorics formula from Unique Paths?

Not directly. The binomial formula counts all right/down paths, and subtracting the ones that hit obstacles needs inclusion-exclusion over obstacles, which is much harder than the DP.