Unique Paths II

Medium Dynamic Programming 2D DP Original on LeetCode

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.

00:00
Testcase

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.

ApproachTimeSpace
Memoised recursionO(m · n)O(m · n)
Optimal (one row)O(m · n)O(n)

1Memoised recursion

TimeO(m · n)
SpaceO(m · n)

paths(i, j) = 0 on an obstacle; otherwise the sum of paths from above and from the left, cached.

  1. 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);
    }
}

2Optimal (one row)

TimeO(m · n)
SpaceO(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.

  1. dp[0] = 1 if the start is open.
  2. 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];
    }
}

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.