Bird
Raised Fist0

Consider the following buggy code for candy distribution. Which line contains the subtle bug that can cause incorrect candy counts?

medium🐞 Bug Identification Q14 of Q15
Greedy Algorithms - Candy Distribution
Consider the following buggy code for candy distribution. Which line contains the subtle bug that can cause incorrect candy counts?
ALine 3: candies initialized with zeros instead of ones
BLine 5: loop starts from 1 instead of 0
CLine 7: candies[i] updated without checking if greater than candies[i-1]
DLine 9: condition candies[i] <= candies[i + 1] missing
Step-by-Step Solution
  1. Step 1: Check initialization of candies array

    Line 3 initializes candies with zeros, violating the problem requirement that each child must have at least one candy.
  2. Step 2: Understand impact of zero initialization

    Zero candies can cause incorrect comparisons and final sums, failing test cases where minimum is 1 per child.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Initialization must be at least 1 per child [OK]
Quick Trick: Candies must start at 1, not 0 [OK]
Common Mistakes:
MISTAKES
  • Forgetting minimum candy per child
  • Incorrect loop boundaries
  • Missing update conditions
Trap Explanation:
PITFALL
  • Zero initialization looks plausible but breaks problem constraints subtly.
Interviewer Note:
CONTEXT
  • Tests if candidate catches subtle initialization bugs violating problem rules.
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