Bird
Raised Fist0

The following code attempts to solve the subset sum problem using space-optimized DP. Identify the bug that causes incorrect results on some inputs.

medium🐞 Bug Identification Q14 of Q15
Dynamic Programming: Knapsack - Subset Sum
The following code attempts to solve the subset sum problem using space-optimized DP. Identify the bug that causes incorrect results on some inputs.
ALine 2: dp[0] should be initialized to False
BLine 6: dp[w] should be assigned dp[w - num] only, not ORed
CLine 4: The outer loop should iterate backwards over nums
DLine 5: The inner loop iterates forwards instead of backwards
Step-by-Step Solution
Solution:
  1. Step 1: Understand dp update direction

    Iterating forwards causes dp[w] to use updated dp[w - num] from the same iteration, leading to overcounting.
  2. Step 2: Correct iteration direction

    Iterating backwards ensures dp[w - num] is from previous iteration, preserving correctness.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Forward iteration breaks subset sum correctness -> bug at line 5 [OK]
Quick Trick: DP must iterate sums backward to avoid reuse in same iteration [OK]
Common Mistakes:
MISTAKES
  • Initializing dp[0] incorrectly
  • Misusing OR in dp update
  • Wrong loop order over nums
Trap Explanation:
PITFALL
  • Forward iteration looks natural but breaks correctness subtly, passing some tests.
Interviewer Note:
CONTEXT
  • Tests candidate's understanding of DP state dependencies and iteration order.
Master "Subset 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