We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Candy

Number: 135

Difficulty: Hard

Paid? No

Companies: Amazon, Google, Meta, TikTok, Salesforce, Bloomberg, PhonePe, Microsoft, Flipkart, Urban Company, Adobe, Yandex, Goldman Sachs, Uber, Oracle, Accenture, Mastercard


Problem Description

There are n children standing in line, each with a rating value provided in an array. The goal is to distribute candies such that each child receives at least one candy and any child with a higher rating than an adjacent child gets more candies than that neighbor. Return the minimum number of candies needed to fulfill these requirements.


Key Insights

  • Every child must get at least one candy.
  • A left-to-right pass ensures that each child has more candies than the left neighbor if their rating is higher.
  • A right-to-left pass ensures that each child has more candies than the right neighbor if their rating is higher.
  • The final candy distribution for each child is determined by taking the maximum candies assigned by the two passes.

Space and Time Complexity

Time Complexity: O(n) - Two passes over the array, each in linear time. Space Complexity: O(n) - An auxiliary array is used to store the candy counts for each child.


Solution

We start by initializing an array with 1 candy for each child, since each child must receive at least one candy. Then, perform a left-to-right pass: if a child’s rating is higher than the previous child, assign one more candy than the previous child. Next, perform a right-to-left pass: if a child’s rating is higher than the next child, update the candy count to be the maximum of its current value or one more than the next child's candy count. The answer is the sum of the adjusted candy counts.


Code Solutions

# Function to distribute candies according to ratings.
def candy(ratings):
    n = len(ratings)
    candies = [1] * n  # Initialize with 1 candy for each child.
    
    # Left-to-right pass: ensure right neighbor condition.
    for i in range(1, n):
        if ratings[i] > ratings[i - 1]:
            candies[i] = candies[i - 1] + 1
    
    # Right-to-left pass: ensure left neighbor condition.
    for i in range(n - 2, -1, -1):
        if ratings[i] > ratings[i + 1]:
            candies[i] = max(candies[i], candies[i + 1] + 1)
    
    # Sum up all distributed candies.
    return sum(candies)

# Example usage:
ratings = [1, 0, 2]
print(candy(ratings))  # Expected Output: 5
← Back to All Questions