Bird
Raised Fist0

The following code attempts to count the number of combinations to make change. Which line contains a subtle bug that causes it to count permutations instead of combinations?

medium🐞 Bug Identification Q14 of Q15
Dynamic Programming: Knapsack - Coin Change II (Count Ways)
The following code attempts to count the number of combinations to make change. Which line contains a subtle bug that causes it to count permutations instead of combinations?
ALine 5: inner loop iterating backwards over amounts
BLine 4: outer loop over coins
CLine 2: dp initialization
DLine 6: updating dp[w] with dp[w - coin]
Step-by-Step Solution
Solution:
  1. Step 1: Understand iteration order effect

    Iterating amounts backwards causes dp to count permutations, not combinations.
  2. Step 2: Identify bug line

    Line 5 iterates w from amount down to coin, which breaks combination counting logic.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Forward iteration over amounts is required to count combinations correctly [OK]
Quick Trick: Check direction of inner loop iteration [OK]
Common Mistakes:
MISTAKES
  • Using backward iteration in 1D dp
  • Misplacing dp[0] initialization
Trap Explanation:
PITFALL
  • Backward iteration looks correct for 0/1 knapsack but breaks unbounded knapsack combination counting.
Interviewer Note:
CONTEXT
  • Tests if candidate knows subtle iteration order impact on counting combinations vs permutations.
Master "Coin Change II (Count Ways)" 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