Bird
Raised Fist0
Interview Prepdp-grid-intervalsmediumAmazonGoogle

Unique Paths II (With Obstacles)

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Steps
setup

Initialize dp array with zeros

Create a dp array of length equal to the number of columns (3), initialized with zeros.

💡 This array will store the number of unique paths to each cell in the current row.
Line:dp = [0]*n
💡 The dp array represents the current state of path counts for each column.
📊
Unique Paths II (With Obstacles) - Watch the Algorithm Execute, Step by Step
Watching each update to the dp array reveals how the algorithm accumulates path counts and handles obstacles, making the dynamic programming logic clear.
Step 1/12
·Active fillAnswer cell
Item 0 - wt:0 val:0
i\w012
i=0000
Item 0 - wt:0 val:1
i\w012
i=0100
start cell
Item 0 - wt:0 val:1
i\w012
i=0100
free cell
Item 0 - wt:0 val:1
i\w012
i=0110
free cell
Item 0 - wt:0 val:1
i\w012
i=0111
free cell
Item 1 - wt:0 val:1
i\w012
i=0111
free cell
Item 1 - wt:0 val:0
i\w012
i=0101
obstacle
Item 1 - wt:0 val:1
i\w012
i=0101
free cell
Item 2 - wt:0 val:1
i\w012
i=0101
free cell
Item 2 - wt:0 val:1
i\w012
i=0111
free cell
Item 2 - wt:0 val:2
i\w012
i=0112
free cell
Item 2 - wt:0 val:2
i\w012
i=0112
answer cell

Key Takeaways

The dp array accumulates the number of unique paths to each cell in the current row, updating in place.

This insight is hard to see from code alone because the dp array is reused and updated dynamically, which can be confusing without visualization.

Obstacles reset dp values to zero, effectively blocking paths through those cells.

Seeing the dp array zeroed at obstacle positions visually clarifies how the algorithm excludes invalid paths.

The final answer is stored in the last element of the dp array after processing all rows.

Understanding that the dp array's last element holds the total paths is easier when watching the final step highlight this cell.

Practice

(1/5)
1. Consider the following snippet from the optimal Zuma Game solution. Given board = "WRRBBW" and hand = "RB", what is the return value of findMinStep(board, hand)?
easy
A. 2
B. -1
C. 3
D. 1

Solution

  1. Step 1: Trace initial calls with board="WRRBBW" and hand="RB"

    Hand has 1 R and 1 B. The board requires more balls to clear groups of 3, but hand is insufficient to clear all.
  2. Step 2: Check if any insertion sequence clears board

    Trying to insert R or B balls to form groups of 3 fails due to insufficient balls; no sequence clears the board fully.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Return -1 indicates no solution with given hand [OK]
Hint: Insufficient hand balls cause no solution -> -1 [OK]
Common Mistakes:
  • Assuming partial removals suffice to clear board
  • Miscounting balls needed for group removal
  • Forgetting to restore hand counts after recursion
2. What is the time complexity of the space-optimized bottom-up DP solution for the Maximal Square problem on an m x n matrix, and why might some candidates incorrectly think it is higher?
medium
A. O(m^3) because checking all squares requires nested loops
B. O(m * n * min(m,n)) because of checking all possible square sizes
C. O(m * n) because each cell is processed once with constant time updates
D. O(m + n) because only rows and columns are iterated separately

Solution

  1. Step 1: Identify loops in the code

    Two nested loops iterate over rows and columns, each cell processed once.
  2. Step 2: Understand DP update cost

    Each dp update is O(1), no nested checks for squares inside loops.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    DP avoids checking all squares explicitly [OK]
Hint: DP processes each cell once with constant work [OK]
Common Mistakes:
  • Confusing brute force with DP complexity
  • Assuming nested loops check all squares
  • Ignoring constant time DP updates
3. The following code attempts to solve the Stone Game problem using bottom-up DP. Identify the line containing the subtle bug that causes incorrect results on some inputs.
def stoneGame(piles):
    n = len(piles)
    dp = [[0]*n for _ in range(n)]
    for i in range(n):
        dp[i][i] = piles[i]
    for length in range(2, n+1):
        for i in range(n - length + 1):
            j = i + length - 1
            dp[i][j] = max(piles[i] + dp[i+1][j], piles[j] + dp[i][j-1])
    return dp[0][n-1] > 0
medium
A. Line computing dp[i][j] = max(piles[i] + dp[i+1][j], piles[j] + dp[i][j-1])
B. Line initializing dp[i][i] = piles[i]
C. Line defining the outer loop for length in range(2, n+1)
D. Line returning dp[0][n-1] > 0

Solution

  1. Step 1: Understand dp state meaning

    dp[i][j] should represent the maximum difference in stones the current player can achieve over the opponent.
  2. Step 2: Identify incorrect recurrence

    The buggy line adds piles[i] + dp[i+1][j], which ignores the opponent's optimal response. The correct formula subtracts dp[i+1][j] to account for opponent's best play.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct recurrence uses subtraction, not addition [OK]
Hint: DP recurrence must subtract opponent's score [OK]
Common Mistakes:
  • Adding dp values instead of subtracting opponent's score
  • Forgetting base case initialization
4. Suppose the Burst Balloons problem is modified so that each balloon can be burst multiple times (reused), and bursting a balloon again yields coins based on the current adjacent balloons. Which of the following changes to the bottom-up DP approach correctly adapts to this variant?
hard
A. Switch to a stateful DP that tracks the count of bursts per balloon and use memoization over these counts
B. Modify the DP to consider only the first burst of each balloon and ignore reuse
C. Use the same interval DP but allow k to be chosen multiple times per interval
D. Use a greedy approach bursting the balloon with the maximum product of neighbors repeatedly

Solution

  1. Step 1: Understand reuse impact

    Allowing multiple bursts per balloon means the problem state must track how many times each balloon has been burst, increasing complexity.
  2. Step 2: Adapt DP state

    Interval DP assuming each balloon bursts once no longer works. We need a DP or memoization that tracks burst counts per balloon to correctly compute coins.
  3. Step 3: Evaluate options

    Switch to a stateful DP that tracks the count of bursts per balloon and use memoization over these counts correctly proposes a stateful DP with counts and memoization. Use the same interval DP but allow k to be chosen multiple times per interval incorrectly reuses interval DP without state changes. Modify the DP to consider only the first burst of each balloon and ignore reuse ignores reuse, and D is greedy and incorrect.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Tracking burst counts is necessary for reuse variants [OK]
Hint: Reuse requires tracking burst counts, not just intervals [OK]
Common Mistakes:
  • Trying naive interval DP for reuse
  • Ignoring state explosion
  • Using greedy for complex DP variants
5. Suppose the Stone Game is modified so that players can pick stones from either end multiple times (i.e., reuse piles after picking). Which of the following changes correctly adapts the DP solution to handle this variant?
hard
A. Use a bottom-up DP with a sliding window over piles, but do not change the recurrence relation
B. Keep the same interval DP but add a loop to consider picking the same pile multiple times in one turn
C. Change dp state to represent maximum difference with unlimited picks and use a 1D dp array updated iteratively
D. Switch to a greedy approach since DP no longer applies when reuse is allowed

Solution

  1. Step 1: Understand the impact of reuse

    Allowing reuse means piles are infinite or replenished, so intervals no longer shrink and the problem resembles unbounded knapsack.
  2. Step 2: Adapt DP state and recurrence

    We need a 1D dp array representing maximum difference for each possible pile count, updated iteratively considering unlimited picks, similar to unbounded knapsack.
  3. Step 3: Reject incorrect options

    Interval DP with multiple picks per turn or unchanged recurrence won't handle reuse correctly; greedy fails due to opponent's optimal play.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Reuse -> unbounded knapsack style DP with 1D array [OK]
Hint: Reuse -> unbounded knapsack DP, not interval DP [OK]
Common Mistakes:
  • Trying to reuse interval DP unchanged
  • Assuming greedy works with reuse