Bird
Raised Fist0

The following code attempts to solve the Equal Partition problem using a 1D DP array. Which line contains a subtle bug that can cause incorrect results on some inputs?

medium🐞 Bug Identification Q14 of Q15
Dynamic Programming: Knapsack - Equal Partition (Partition Equal Subset Sum)
The following code attempts to solve the Equal Partition problem using a 1D DP array. Which line contains a subtle bug that can cause incorrect results on some inputs?
def canPartition(nums):
    total = sum(nums)
    target = total // 2
    dp = [False] * (target + 1)
    dp[0] = True

    for num in nums:
        for w in range(num, target + 1):
            dp[w] = dp[w] or dp[w - num]

    return dp[target]
ALine 2: Missing check if total is even before proceeding
BLine 4: Initializing dp array with false instead of true
CLine 6: Iterating forwards in dp array instead of backwards
DLine 8: Returning dp[target] without verifying dp array correctness
Step-by-Step Solution
Solution:
  1. Step 1: Identify missing even check

    Line 2 does not check if total is even, but this causes no incorrect dp updates, only wasted computation.
  2. Step 2: Analyze dp iteration direction

    Line 6 iterates forwards, which causes reuse of updated dp values in the same iteration, leading to counting elements multiple times and incorrect results.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Backward iteration is required to avoid reusing updated dp values in the same iteration [OK]
Quick Trick: DP must iterate backwards to avoid reuse in 1D array [OK]
Common Mistakes:
MISTAKES
  • Iterating forwards in dp updates
  • Skipping even sum check
Trap Explanation:
PITFALL
  • Forwards iteration looks natural but breaks 0/1 knapsack logic by reusing updated states
Interviewer Note:
CONTEXT
  • Checks if candidate knows subtle DP update order bugs that cause wrong answers
Master "Equal Partition (Partition Equal 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