Bird
Raised Fist0

Identify the line containing the subtle bug that can cause incorrect results or infinite loops.

medium🐞 Bug Identification Q14 of Q15
Dynamic Programming: Knapsack - Partition to K Equal Sum Subsets
The following code attempts to solve the Partition to K Equal Sum Subsets problem using DP with bitmask tabulation. Identify the line containing the subtle bug that can cause incorrect results or infinite loops.
def canPartitionKSubsets(nums, k):
    total = sum(nums)
    if total % k != 0:
        return False
    target = total // k
    n = len(nums)
    nums.sort()
    if nums[-1] > target:
        return False

    dp = [-1] * (1 << n)
    dp[0] = 0

    for mask in range(1 << n):
        if dp[mask] == -1:
            continue
        for i in range(n):
            if (mask & (1 << i)) == 0 and dp[mask] + nums[i] <= target:
                next_mask = mask | (1 << i)
                dp[next_mask] = (dp[mask] + nums[i]) % target

    return dp[(1 << n) - 1] == 0
ALine: dp = [-1] * (1 << n)
BLine: if dp[next_mask] == -1: (missing in this code)
CLine: nums.sort()
DLine: dp[next_mask] = (dp[mask] + nums[i]) % target
Step-by-Step Solution
  1. Step 1: Identify missing condition

    The code lacks a check if dp[next_mask] is already set, so it overwrites states, causing incorrect results.
  2. Step 2: Pinpoint the buggy line

    The line assigning dp[next_mask] unconditionally overwrites previous valid states, breaking memoization.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Adding "if dp[next_mask] == -1:" before assignment fixes bug [OK]
Quick Trick: Always check if dp state is unset before assignment [OK]
Common Mistakes:
MISTAKES
  • Overwriting dp states without checking leads to incorrect answers
  • Not pruning symmetric states increases runtime
Trap Explanation:
PITFALL
  • Missing dp[next_mask] == -1 check looks subtle but breaks correctness.
Interviewer Note:
CONTEXT
  • Tests if candidate can spot subtle memoization bugs that pass many tests but fail edge cases.
Master "Partition to K Equal Sum Subsets" 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