Bird
Raised Fist0

Which line contains a subtle bug that can cause incorrect candy assignments?

medium🐛 Buggy Code Q7 of Q15
Greedy Algorithms - Candy Distribution
Examine the following candy distribution code snippet. Which line contains a subtle bug that can cause incorrect candy assignments? ```python def candy(ratings): n = len(ratings) candies = [1] * n for i in range(1, n): if ratings[i] > ratings[i - 1]: candies[i] = candies[i - 1] + 1 for i in range(n - 2, -1, -1): if ratings[i] > ratings[i + 1]: candies[i] = candies[i + 1] + 1 return sum(candies) ```
ALine updating candies[i] in the second for-loop without max()
BInitialization of candies array with ones
CFirst for-loop condition checking ratings[i] > ratings[i - 1]
DReturn statement summing candies
Step-by-Step Solution
Solution:
  1. Step 1: Understand second pass

    The second loop updates candies[i] if ratings[i] > ratings[i+1].
  2. Step 2: Identify bug

    It assigns candies[i] = candies[i+1] + 1 without comparing with existing candies[i].
  3. Step 3: Correct approach

    Should use candies[i] = max(candies[i], candies[i+1] + 1) to avoid lowering candies.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Missing max() causes candy count to decrease incorrectly [OK]
Quick Trick: Always use max() in second pass to avoid lowering candies [OK]
Common Mistakes:
MISTAKES
  • Ignoring max() causes candy counts to decrease
  • Thinking initialization is the bug
  • Misreading loop conditions
Trap Explanation:
PITFALL
  • Assigning without max() looks correct but breaks candy constraints
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle bugs in greedy candy distribution code
Master "Candy Distribution" in Greedy Algorithms

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 Greedy Algorithms Quizzes