KatInterview

63. Unique Paths II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

This problem is a variation of the classic "Unique Paths" problem. We need to find the number of unique paths from the top-left corner to the bottom-right corner of a grid. The robot can only move down or right. The new constraint is that some cells in the grid are obstacles, which cannot be part of any path.

Solution

Unique Paths II in Python

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        m = len(obstacleGrid)
        n = len(obstacleGrid[0])

        # If the starting cell is an obstacle, no path is possible.
        if obstacleGrid[0][0] == 1:
            return 0
        
        # A 1D dp array of size n, representing one row's path counts.
        dp = [0] * n
        # Base case: one way to reach the start cell (by being there).
        dp[0] = 1

        for i in range(m):
            for j in range(n):
                # If there's an obstacle, the number of paths to this cell is 0.
                if obstacleGrid[i][j] == 1:
                    dp[j] = 0
                # Otherwise, paths to this cell = paths from top + paths from left.
                # dp[j] already contains paths from top. We add paths from left (dp[j-1]).
                # This update is skipped for the first column (j=0) since it has no left cell.
                elif j > 0:
                    dp[j] += dp[j-1]
        
        # The last element holds the total paths to the bottom-right corner.
        return dp[n-1]

Unique Paths II in Java

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;

        // If the starting cell is an obstacle, no paths are possible.
        if (obstacleGrid[0][0] == 1) {
            return 0;
        }

        // DP array to store the number of paths for the current row being processed.
        int[] dp = new int[n];
        
        // Base case: One path to the starting cell.
        dp[0] = 1;

        // Iterate over the grid, row by row.
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // If there's an obstacle, no paths can reach this cell.
                if (obstacleGrid[i][j] == 1) {
                    dp[j] = 0;
                } else if (j > 0) {
                    // Paths to (i, j) = paths from (i-1, j) + paths from (i, j-1)
                    // dp[j] already holds paths from (i-1, j) (from the previous row's calculation)
                    // dp[j-1] holds paths from (i, j-1) for the current row i
                    dp[j] = dp[j] + dp[j-1];
                }
            }
        }

        // Return the number of paths to the bottom-right cell.
        return dp[n - 1];
    }
}

Unique Paths II in C++

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();

        // If the starting cell has an obstacle, then there are no paths.
        if (obstacleGrid[0][0] == 1) {
            return 0;
        }

        // Use a vector as a 1D DP array. The size is n (number of columns).
        // The problem statement guarantees the answer fits in an int, so long is not strictly necessary but is safer against overflow.
        vector<int> dp(n, 0);

        // Base case: There's one way to reach the starting cell (by being there).
        dp[0] = 1;

        // Iterate through each cell of the grid.
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                // If the cell contains an obstacle, no paths can reach it.
                if (obstacleGrid[i][j] == 1) {
                    dp[j] = 0;
                } else if (j > 0) {
                    // The number of paths to the current cell is the sum of paths from:
                    // 1. The cell above (the old dp[j] value)
                    // 2. The cell to the left (the new dp[j-1] value)
                    dp[j] = dp[j] + dp[j-1];
                }
            }
        }

        // The last element of dp will hold the total number of paths to the bottom-right corner.
        return dp[n - 1];
    }
};

Unique Paths II in TypeScript

function uniquePathsWithObstacles(obstacleGrid: number[][]): number {
    const m = obstacleGrid.length;
    const n = obstacleGrid[0].length;

    // If the starting cell has an obstacle, return 0 as no path can be formed.
    if (obstacleGrid[0][0] === 1) {
        return 0;
    }

    // DP array to store path counts for the current row being processed.
    const dp: number[] = new Array(n).fill(0);
    // Base case: There's one way to be at the starting cell.
    dp[0] = 1;

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            // If the cell is an obstacle, no paths can go through it.
            if (obstacleGrid[i][j] === 1) {
                dp[j] = 0;
            } else if (j > 0) {
                // Number of paths is sum of paths from cell above and cell to the left.
                // dp[j] currently holds paths from the cell above (from previous row's calculation).
                // dp[j-1] holds paths from the cell to the left (for the current row).
                dp[j] = dp[j] + dp[j - 1];
            }
        }
    }

    // The last element contains the total number of paths to the destination.
    return dp[n - 1];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.