Press enter to see results or esc to cancel.

Unique Paths II Leetcode Problem 63 [Python Solution]

Lets get solving the Unique Paths II problem, which is a medium-level challenge falling under the category of 2-D Dynamic Programming.

The problem presents a scenario where you are given an M x N grid, and your goal is to calculate the number of unique paths a robot can take from the top-left corner to the bottom-right corner.

The robot can only move down or to the right at any given point in time, and certain grid cells are blocked with obstacles (marked as 1) while others are open spaces (marked as 0).

Your task is to find the number of valid paths, considering the obstacles, and return this count.

Example 1:

Input:

obstacleGrid = [[0,0,0],
                [0,1,0],
                [0,0,0]]

Output: 2

Explanation: There is one obstacle in the middle of the 3×3 grid.

There are two ways to reach the bottom-right corner:

  1. Right -> Right -> Down -> Down
  2. Down -> Down -> Right -> Right

Example 2:

Input:

obstacleGrid = [[0,1],
                [0,0]]

Output: 1

Constraints:

  • m == obstacleGrid.length
  • n == obstacleGrid[i].length
  • 1 <= m, n <= 100
  • obstacleGrid[i][j] is 0 or 1.

Understanding Unique Paths II Constraints

To efficiently solve the Unique Paths II problem, it’s important to understand the constraints involved.

These constraints guide our approach to finding a solution:

  • The grid dimensions are between 1×1 and 100×100, which means we can have grids of various sizes.
  • The robot can only move down or to the right, ensuring a straightforward path.
  • Obstacles are marked as 1, which restricts movement through specific grid cells.

Unique Paths II LeetCode Problem Solution

Now, let’s explore the solutions to this problem.

We’ll discuss a Bruteforce Approach followed by a more Efficient Approach using Dynamic Programming (DP).

1. Bruteforce Approach

The most straightforward way to tackle this problem is through recursion and a depth-first search (DFS) approach.

We’ll start from the top-left corner and recursively explore both down and right directions, counting the number of unique paths.

Here’s a Python code snippet demonstrating the Bruteforce Approach:

def uniquePathsWithObstacles(self, grid: List[List[int]]) -> int:
    M, N = len(grid), len(grid[0])

    # Recursive DFS function
    def dfs(r, c):
        # Base cases:
        if r == M or c == N or grid[r][c]:
            return 0
        if r == M - 1 and c == N - 1:
            return 1

        # Recursive exploration
        return dfs(r + 1, c) + dfs(r, c + 1)

    return dfs(0, 0)

This solution is simple to understand and implement but becomes inefficient for larger grids with many obstacles.

To optimize the solution, we can use Dynamic Programming.

2. An Efficient Approach with Dynamic Programming

Dynamic Programming is an effective technique for optimizing problems like this.

It eliminates redundant computations by storing and reusing previously calculated results.

For this problem, we can use a 2D DP array to keep track of the number of unique paths for each cell.

Here’s a Python code snippet demonstrating the Efficient DP Approach:

def uniquePathsWithObstacles(self, obstacleGrid: List&#91;List&#91;int]]) -> int:
        M, N = len(obstacleGrid), len(obstacleGrid&#91;0])
        dp = &#91;&#91;0] * N for _ in range(M)]

        # Initialize the bottom-right cell
        dp&#91;M-1]&#91;N-1] = 1

        # Iterate through the grid in reverse order
        for r in reversed(range(M)):
            for c in reversed(range(N)):
                if obstacleGrid&#91;r]&#91;c]:
                    dp&#91;r]&#91;c] = 0
                else:
                    if r + 1 &lt; M:
                        dp&#91;r]&#91;c] += dp&#91;r + 1]&#91;c]
                    if c + 1 &lt; N:
                        dp&#91;r]&#91;c] += dp&#91;r]&#91;c + 1]

        return dp&#91;0]&#91;0]

This Dynamic Programming approach efficiently calculates the number of unique paths by filling the DP array from the bottom-right cell to the top-left cell.

It considers the presence of obstacles and handles edge cases gracefully.

Time and Space Complexity

For the Efficient Dynamic Programming solution, let’s analyze the time and space complexity:

  • Time Complexity: The code runs in O(M * N) time, where M is the number of rows and N is the number of columns in the grid.

We traverse the entire grid once.

  • Space Complexity: The space complexity is O(M * N) because we use a 2D DP array to store the results for each cell in the grid.

Reasoning Behind Our Approach

The key to this efficient solution is recognizing that we can fill the DP array in place without requiring more than one row in memory at a time.

By considering the constraints and optimizing the solution through dynamic programming, we can efficiently compute the number of unique paths while accounting for obstacles in the grid.

In conclusion, the Unique Paths II problem can be solved efficiently using dynamic programming.

We calculate the number of unique paths from the top-left to the bottom-right corner of a grid, considering obstacles and constraints.

The code and explanations provided in this blog post should help you understand and solve this problem effectively.

If you found this blog post helpful, please like and engage for more coding challenges and solutions.

For additional resources and coding interview preparation, check out neatcode.io.

Happy coding!

Related Interview Questions By Company:

Related Interview Questions By Difficulty:

Related Interview Questions By Category:

Conclusion

In this blog post, we explored the Unique Paths II problem, discussed its constraints, and presented an efficient Python solution using Dynamic Programming.

We hope this guide helps you understand the problem and how to approach it optimally.

If you have any questions, suggestions, or want to discuss further, please feel free to comment.

We encourage your engagement and sharing of this content to help others in their coding journey.

To access the original problem statement and further details, you can visit the Unique Paths II problem on LeetCode.

Thank you for reading, and happy coding!

>