Bird
Raised Fist0

The following code attempts to solve the Target Sum problem using bottom-up DP with offset indexing. Which line contains a subtle bug that causes incorrect results on inputs containing zero?

medium🐞 Bug Identification Q14 of Q15
Dynamic Programming: Knapsack - Target Sum
The following code attempts to solve the Target Sum problem using bottom-up DP with offset indexing. Which line contains a subtle bug that causes incorrect results on inputs containing zero?
ALine 12-15: Updating dp array in-place instead of using a separate next_dp
BLine 6: dp[offset] = 1
CLine 10: if dp[s] != 0:
DLine 8: for num in nums:
Step-by-Step Solution
  1. Step 1: Identify DP update method

    The code updates dp in-place during iteration over sums, causing double counting when num=0 or overlapping states.
  2. Step 2: Understand impact on zero values

    Zero does not change sum, so updating dp in-place doubles counts incorrectly. Using a separate next_dp array avoids this.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    In-place updates cause state reuse within iteration, breaking correctness [OK]
Quick Trick: In-place dp updates cause double counting with zero values [OK]
Common Mistakes:
MISTAKES
  • Not using a separate dp array for next iteration
Trap Explanation:
PITFALL
  • In-place updates look efficient but break correctness for zero or overlapping sums.
Interviewer Note:
CONTEXT
  • Tests if candidate spots subtle DP update bugs affecting correctness.
Master "Target Sum" in Dynamic Programming: Knapsack

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Dynamic Programming: Knapsack Quizzes