← Back to index
MediumPython3 min read

Unique Paths II

count paths from top-left to bottom-right with obstacles using dp with space optimization to O(n).

dynamic-programmingmatrix

Problem link

View on LeetCode

Solutions in this repo

  • Python../unique-paths-ii/solution.pyPython solution

use 1d dp array to track paths for current row. initialize dp[0] = 1 if start is not obstacle, else 0. for each row, if cell is obstacle, set dp[c] = 0. otherwise, dp[c] += dp[c-1] (paths from left).

for first column (c=0), only update from top (previous dp[0]). for other columns, add paths from left. space optimized from O(mn) to O(n) by processing row by row.

optimization

since we only need previous row values, use single array and update in-place. obstacle cells reset path count to 0.

complexity

O(mn) time, O(n) space where m and n are grid dimensions. efficient space-optimized dp.