Unique Paths II
Unique Paths II is a medium dynamic programming problem solved with the 2d dp pattern.
The best approach, optimal (one row), runs in O(m · n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from memoised recursion up.
Problem
Same as Unique Paths, but some cells contain obstacles (1) that the robot cannot enter. Count the paths from the top-left to the bottom-right.
Examples
Example 1
- Input
obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]- Output
2
Example 2
- Input
obstacleGrid = [[0,1],[0,0]]- Output
1
Constraints
1 <= m, n <= 100; 1 marks an obstacle.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Memoised recursion | O(m · n) | O(m · n) |
| Optimal (one row) | O(m · n) | O(n) |
1Memoised recursion
O(m · n)O(m · n)paths(i, j) = 0 on an obstacle; otherwise the sum of paths from above and from the left, cached.
- Out of bounds or obstacle → 0; (0, 0) → 1.
class Solution {
private Integer[][] memo;
public int uniquePathsWithObstacles(int[][] g) {
memo = new Integer[g.length][g[0].length];
return paths(g, g.length - 1, g[0].length - 1);
}
private int paths(int[][] g, int i, int j) {
if (i < 0 || j < 0 || g[i][j] == 1) return 0;
if (i == 0 && j == 0) return 1;
if (memo[i][j] != null) return memo[i][j];
return memo[i][j] = paths(g, i - 1, j) + paths(g, i, j - 1);
}
}class Solution:
def uniquePathsWithObstacles(self, g: List[List[int]]) -> int:
self.memo = [[None] * len(g[0]) for _ in range(len(g))]
return self.paths(g, len(g) - 1, len(g[0]) - 1)
def paths(self, g: List[List[int]], i: int, j: int) -> int:
if i < 0 or j < 0 or g[i][j] == 1:
return 0
if i == 0 and j == 0:
return 1
if self.memo[i][j] is not None:
return self.memo[i][j]
self.memo[i][j] = self.paths(g, i - 1, j) + self.paths(g, i, j - 1)
return self.memo[i][j]class Solution {
vector<vector<int>> memo;
public:
int uniquePathsWithObstacles(vector<vector<int>>& g) {
memo.assign(g.size(), vector<int>(g[0].size(), -1));
return paths(g, g.size() - 1, g[0].size() - 1);
}
private:
int paths(vector<vector<int>>& g, int i, int j) {
if (i < 0 || j < 0 || g[i][j] == 1) return 0;
if (i == 0 && j == 0) return 1;
if (memo[i][j] != -1) return memo[i][j];
return memo[i][j] = paths(g, i - 1, j) + paths(g, i, j - 1);
}
};function uniquePathsWithObstacles(g) {
const memo = Array.from({ length: g.length }, () => new Array(g[0].length).fill(null));
function paths(g, i, j) {
if (i < 0 || j < 0 || g[i][j] === 1) return 0;
if (i === 0 && j === 0) return 1;
if (memo[i][j] !== null) return memo[i][j];
return memo[i][j] = paths(g, i - 1, j) + paths(g, i, j - 1);
}
return paths(g, g.length - 1, g[0].length - 1);
}2Optimal (one row)
O(m · n)O(n)dp[j] = ways to reach column j in the current row. An obstacle sets it to 0; otherwise add the value to the left.
- dp[0] = 1 if the start is open.
- For each cell: obstacle → dp[j] = 0; else if j > 0, dp[j] += dp[j - 1].
class Solution {
public int uniquePathsWithObstacles(int[][] g) {
int n = g[0].length;
int[] dp = new int[n];
dp[0] = g[0][0] == 1 ? 0 : 1;
for (int[] row : g)
for (int j = 0; j < n; j++) {
if (row[j] == 1) dp[j] = 0;
else if (j > 0) dp[j] += dp[j - 1];
}
return dp[n - 1];
}
}class Solution:
def uniquePathsWithObstacles(self, g: List[List[int]]) -> int:
n = len(g[0])
dp = [0] * n
dp[0] = 0 if g[0][0] == 1 else 1
for row in g:
for j in range(n):
if row[j] == 1:
dp[j] = 0
elif j > 0:
dp[j] += dp[j - 1]
return dp[n - 1]class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& g) {
int n = g[0].size();
vector<int> dp(n, 0);
dp[0] = g[0][0] == 1 ? 0 : 1;
for (auto& row : g)
for (int j = 0; j < n; j++) {
if (row[j] == 1) dp[j] = 0;
else if (j > 0) dp[j] += dp[j - 1];
}
return dp[n - 1];
}
};function uniquePathsWithObstacles(g) {
const n = g[0].length;
const dp = new Array(n).fill(0);
dp[0] = g[0][0] === 1 ? 0 : 1;
for (const row of g)
for (let j = 0; j < n; j++) {
if (row[j] === 1) dp[j] = 0;
else if (j > 0) dp[j] += dp[j - 1];
}
return dp[n - 1];
}Edge cases to test
- Start or end is an obstacle (0 paths)
- An obstacle in the first row blocks every cell to its right
Hints
Hint 1
Same DP as Unique Paths, but a blocked cell has 0 ways.
FAQ
What is the best time complexity for Unique Paths II?
Optimal (one row) runs in O(m · n) time and O(n) extra space.
Which pattern does Unique Paths II use?
It is a dynamic programming problem that uses the 2d dp pattern. Other problems with the same pattern: Minimum Path Sum, Unique Paths, Dungeon Game.
Is there a brute force solution for Unique Paths II?
Yes. Memoised recursion takes O(m · n) time and O(m · n) space. paths(i, j) = 0 on an obstacle; otherwise the sum of paths from above and from the left, cached.
Which edge cases should I test for Unique Paths II?
Start or end is an obstacle (0 paths); An obstacle in the first row blocks every cell to its right.