#63

Unique Paths II

Medium
ArrayDynamic ProgrammingMatrixDynamic ProgrammingGrid Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^(m+n))
O(m*n)
Space
O(m+n)
O(m*n)
💡

Intuition

Time O(m*n)Space O(m*n)

The optimal solution uses dynamic programming to build a table that keeps track of the number of unique paths to each cell. By using previously computed values, we avoid redundant calculations and significantly reduce the time complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a 2D DP array of the same size as the grid initialized to 0.
  2. 2Step 2: Set dp[0][0] to 1 if the starting cell is not an obstacle.
  3. 3Step 3: Iterate through each cell in the grid. If the cell is not an obstacle, update dp[i][j] as the sum of dp[i-1][j] and dp[i][j-1] (if within bounds).
  4. 4Step 4: Return the value at dp[m-1][n-1] as the result.
solution.py14 lines
1def uniquePathsWithObstacles(grid):
2    m, n = len(grid), len(grid[0])
3    dp = [[0] * n for _ in range(m)]
4    dp[0][0] = 1 if grid[0][0] == 0 else 0
5    for i in range(m):
6        for j in range(n):
7            if grid[i][j] == 1:
8                dp[i][j] = 0
9            else:
10                if i > 0:
11                    dp[i][j] += dp[i - 1][j]
12                if j > 0:
13                    dp[i][j] += dp[i][j - 1]
14    return dp[m - 1][n - 1]

Complexity note: This complexity is due to the need to fill a 2D DP array of size m*n, where each cell is processed once.

  • 1Dynamic programming is essential for optimizing recursive problems with overlapping subproblems.
  • 2Understanding how to build a DP table can greatly simplify pathfinding problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.