MEDIUM Dynamic Programming 2D

63. Unique Paths II

๐Ÿ“– Problem

You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. An obstacle and space is marked as 1 and 0 respectively in the grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขArray DP table updates
  • โ€ขState transition thinking
  • โ€ขBase case initialization

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Dynamic Programming reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use DP where dp[i][j] represents number of ways to reach cell (i,j)
  • โ†’ If cell is obstacle, dp[i][j] = 0
  • โ†’ Otherwise, dp[i][j] = dp[i-1][j] + dp[i][j-1]
  • โ†’ Time: O(m * n), Space: O(m * n) or O(n) optimized

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse DP where dp[i][j] represents number of ways to reach cell (i,j)
  • โ€ขIf cell is obstacle, dp[i][j] = 0
  • โ€ขOtherwise, dp[i][j] = dp[i-1][j] + dp[i][j-1]

Common Pitfalls

  • โ€ขTime: O(m * n), Space: O(m * n) or O(n) optimized

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
uniquePathsWithObstacles([[0,0,0],[0,1,0],[0,0,0]]);
Expected:
2
Test Case 2
Not run
Input:
uniquePathsWithObstacles([[0,1],[0,0]]);
Expected:
1
Test Case 3
Not run
Input:
uniquePathsWithObstacles([[0,0]]);
Expected:
1

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit