Bird
Raised Fist0

Consider the following Python code for the Equal Partition problem. What is the value of dp[target] after processing the input [1, 5, 11, 5]?

easy🧾 Code Trace Q12 of Q15
Dynamic Programming: Knapsack - Equal Partition (Partition Equal Subset Sum)
Consider the following Python code for the Equal Partition problem. What is the value of dp[target] after processing the input [1, 5, 11, 5]?
def canPartition(nums):
    total = sum(nums)
    if total % 2 != 0:
        return False
    target = total // 2
    dp = [False] * (target + 1)
    dp[0] = True

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

    return dp[target]

print(canPartition([1,5,11,5]))
Atrue
Bfalse
Cnull (error occurs)
DDepends on order of iteration
Step-by-Step Solution
Solution:
  1. Step 1: Calculate total and target

    The total sum is 1 + 5 + 11 + 5 = 22, which is even, so target = 11.
  2. Step 2: Trace dp array updates for each num

    After processing all nums, dp[11] becomes True because subset {11} or {5,5,1} sums to 11.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Input is classic example where partition exists; dp[target] is True [OK]
Quick Trick: Sum is even and dp[target] tracks subset sums [OK]
Common Mistakes:
MISTAKES
  • Confusing dp[target] with dp[target-1]
  • Forgetting to iterate backwards in dp update
Trap Explanation:
PITFALL
  • Some think dp[target] remains false due to off-by-one or forward iteration errors
Interviewer Note:
CONTEXT
  • Checks candidate's ability to mentally execute DP code and understand dp array meaning
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