Bird
Raised Fist0

Examine the following Python code snippet for a space-optimized 0/1 Knapsack implementation. Identify the bug that causes incorrect results:

medium🐞 Bug Identification Q7 of Q15
Dynamic Programming: Knapsack - 0/1 Knapsack Problem
Examine the following Python code snippet for a space-optimized 0/1 Knapsack implementation. Identify the bug that causes incorrect results:
def knapsack_bug(weights, values, W):
    n = len(weights)
    dp = [0] * (W + 1)
    for i in range(n):
        for w in range(weights[i], W + 1):
            dp[w] = max(dp[w], dp[w - weights[i]] + values[i])
    return dp[W]
AThe dp array should be initialized with -1 instead of 0
BThe inner loop should iterate backwards from W down to weights[i]
CThe outer loop should iterate over weights instead of items
DThe function should return dp[0] instead of dp[W]
Step-by-Step Solution
Solution:
  1. Step 1: Understand DP update dependency

    In space-optimized 0/1 Knapsack, dp[w] depends on dp[w - weights[i]] from previous iteration.
  2. Step 2: Identify loop direction

    Iterating forwards overwrites dp values needed for future computations, causing incorrect results.
  3. Step 3: Correct loop direction

    Iterate backwards from W down to weights[i] to preserve previous state during updates.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Forward iteration corrupts dp state [OK]
Quick Trick: Iterate backwards in dp array to avoid overwriting [OK]
Common Mistakes:
MISTAKES
  • Iterating forwards in dp array causing state corruption
  • Incorrect dp initialization values
  • Returning wrong dp index
Trap Explanation:
PITFALL
  • Forward iteration overwrites dp states needed for correct calculation.
Interviewer Note:
CONTEXT
  • Tests understanding of correct iteration order in space-optimized 0/1 Knapsack.
Master "0/1 Knapsack Problem" 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