Bird
Raised Fist0

The following code attempts to solve the coin change minimum coins problem. Identify the line containing the subtle bug that causes incorrect results or infinite recursion for amount=0.

medium🐞 Bug Identification Q14 of Q15
Dynamic Programming: Knapsack - Coin Change (Minimum Coins)
The following code attempts to solve the coin change minimum coins problem. Identify the line containing the subtle bug that causes incorrect results or infinite recursion for amount=0.
def coinChange(coins, amount):
    def dfs(rem):
        if rem == 0:
            return 0
        res = float('inf')
        for coin in coins:
            if rem - coin >= 0:
                res = min(res, 1 + dfs(rem - coin))
        return res
    ans = dfs(amount)
    return ans if ans != float('inf') else -1
ALine 3: Missing base case for rem < 0
BLine 6: Missing check for rem == 0 before recursion
CLine 9: Returning res without checking if res is still infinity
DLine 7: Incorrect condition rem - coin >= 0 instead of rem >= coin
Step-by-Step Solution
Solution:
  1. Step 1: Analyze base cases in recursion

    Code handles rem == 0 but lacks base case for rem < 0, but since rem - coin >= 0 check prevents negative rem, no infinite recursion occurs.
  2. Step 2: Check return value correctness

    Returning res directly without checking if res is still infinity can cause incorrect results when no valid coin combination exists.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Must check if res is infinity before returning to handle no solution cases correctly [OK]
Quick Trick: Check if result is infinity before returning in recursion [OK]
Common Mistakes:
MISTAKES
  • Forgetting to handle no solution case
  • Assuming rem == 0 base case suffices
Trap Explanation:
PITFALL
  • Candidates often miss that returning infinity without check leads to wrong answers when no combination exists.
Interviewer Note:
CONTEXT
  • Tests candidate's attention to recursion return values and edge cases.
Master "Coin Change (Minimum Coins)" 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