Taro Logo

Candy

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+16
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.5K views
Topics:
ArraysGreedy Algorithms

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

Return the minimum number of candies you need to have to distribute the candies to the children.

Example 1:

Input: ratings = [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: ratings = [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.

Constraints:

  • n == ratings.length
  • 1 <= n <= 2 * 104
  • 0 <= ratings[i] <= 2 * 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be the return value if the input array of ratings is empty?
  2. Can the ratings array contain negative numbers or zeros, or are they strictly positive integers?
  3. How should adjacent children with the exact same rating be handled? Do they need to receive the same number of candies, or can one receive more than the other?
  4. Is the line of children considered strictly linear (open-ended), or does it form a circular arrangement?
  5. If multiple valid distributions of candies satisfy the conditions resulting in the same minimum total, does it matter which one we base our calculation on, as long as the sum is minimized?

Brute Force Solution

Approach

Imagine you need to distribute candies to a line of children based on their scores, where higher-scoring children get more candies than their immediate neighbors. The brute force approach involves testing every possible combination of candy amounts for each child until you find a valid distribution that uses the fewest total candies.

Here's how the algorithm would work step-by-step:

  1. Start by giving every single child a temporary starting amount of candies, such as one each.
  2. Check if this setup follows all the rules, meaning every child with a higher score than a neighbor actually has more candies than that neighbor.
  3. If the rules are broken anywhere, adjust the candy amounts slightly for one or more children.
  4. Repeat this process of adjusting and checking every imaginable combination of candy amounts for the entire line of children.
  5. Keep a record of all the combinations that successfully satisfy the neighborhood score rules.
  6. Compare all the successful combinations to see which one used the grand total lowest number of candies.
  7. Select that absolute minimum combination as your final answer.

Code Implementation

def candy(ratings):
    # We use recursion to generate and test every single valid candy distribution permutation
    def generate_distributions(current_index, current_distribution):
        if current_index == len(ratings):
            if satisfies_rules(current_distribution):
                valid_combinations.append(list(current_distribution))
            return

        for candy_amount in range(1, len(ratings) + 1):
            current_distribution.append(candy_amount)
            generate_distributions(current_index + 1, current_distribution)
            current_distribution.pop()

    def satisfies_rules(distribution):
        for index in range(len(ratings)):
            if index > 0 and ratings[index] > ratings[index - 1] and distribution[index] <= distribution[index - 1]:
                return False
            if index < len(ratings) - 1 and ratings[index] > ratings[index + 1] and distribution[index] <= distribution[index + 1]:
                return False
        return True

    valid_combinations = []
    generate_distributions(0, [])

    # We compare all successful combinations to isolate the one consuming the absolute minimum total candies
    minimum_total_candies = float('inf')
    for combination in valid_combinations:
        total_candies = sum(combination)
        if total_candies < minimum_total_candies:
            minimum_total_candies = total_candies

    return minimum_total_candies

Big(O) Analysis

Time Complexity
O(n^m) – The brute force strategy requires testing every possible combination of candy amounts for the n children. Since each child can theoretically take a wide range of candy values up to the maximum score constraint, we explore an exponential or factorial number of configurations. For each configuration, we validate the neighborhood rules across all n children, leading to an extremely high cost driven by nested exploration of every imaginable distribution. As the number of children n increases, the total operations grow exponentially rather than polynomially, reflecting a combinatorial search space.
Space Complexity
O(n) – The brute force approach described requires maintaining a record of all successful candy combinations and checking multiple intermediate trial configurations for the line of children. As the input size N grows, storing these potential candidate distributions and tracking adjustments for all N children demands extra memory that scales linearly. Therefore, the auxiliary space complexity is O(N) to store the various combinations and evaluation states.

Optimal Solution

Approach

Instead of trying to figure out everyone's candy amount all at once, the optimal approach breaks the puzzle down by looking at neighbors in two separate passes. First, we ensure that anyone with a higher score than the person immediately to their left gets more candy than that neighbor, and then we do a second pass from the other direction to fix the right-hand neighbors.

Here's how the algorithm would work step-by-step:

  1. Line up everyone in a single row just like they are standing in real life.
  2. Give every single person a baseline of exactly one piece of candy to start.
  3. Walk down the line from the very beginning to the very end, checking each person against the person standing immediately to their left.
  4. If the person you are looking at has a higher score than their left neighbor, give them one more piece of candy than that neighbor currently has.
  5. Now turn around and walk backward from the very end of the line all the way back to the start, this time checking each person against the person standing immediately to their right.
  6. If the person you are looking at has a higher score than their right neighbor, make sure they have more candy than that right neighbor, but only if they do not already have enough.
  7. Add up every piece of candy assigned across all the people to get the final total needed.

Code Implementation

class Solution:
    def candy(self, ratings: list[int]) -> int:
        total_children = len(ratings)
        candy_allocations = [1] * total_children

        # Enforce left-to-right rule so higher rated children get more than left neighbor.
        for current_index in range(1, total_children):
            if ratings[current_index] > ratings[current_index - 1]:
                candy_allocations[current_index] = candy_allocations[current_index - 1] + 1

        # Enforce right-to-left rule to satisfy conditions relative to right neighbor.
        for current_index in range(total_children - 2, -1, -1):
            if ratings[current_index] > ratings[current_index + 1]:
                if candy_allocations[current_index] <= candy_allocations[current_index + 1]:
                    candy_allocations[current_index] = candy_allocations[current_index + 1] + 1

        # Sum all individual allocations to determine the absolute minimum total required.
        return sum(candy_allocations)

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by the number of children, represented as n, and our linear passes over their ratings. First, we initialize an array of size n and perform a forward pass comparing each child to their left neighbor, taking linear time. Next, we execute a backward pass from the end of the line to the start, checking each child against their right neighbor in another linear scan. Finally, we sum the candy array in one more pass of size n, resulting in approximately 3n operations. Because constant multipliers are dropped in asymptotic analysis, this scales linearly to O(n).
Space Complexity
O(n) – The auxiliary space is driven by a single temporary array of size N, which holds the candy count for each person and starts with a baseline of one piece. During the two passes across the line, this array is modified in place to satisfy the neighbor conditions without needing any additional data structures. Because the array scales directly with the number of people, denoted as N, the total extra memory grows linearly.

Edge Cases

Empty or null ratings array
How to Handle:
Return zero immediately as no children need candy.
Single child rating
How to Handle:
Return one because the single child must receive the minimum requirement of one candy.
Two children with identical ratings
How to Handle:
Assign one candy to each since neither has a strictly higher rating than the other.
All children have identical ratings
How to Handle:
The two-pass algorithm assigns one candy to every child since no neighbor has a strictly higher rating.
Strictly monotonically increasing ratings
How to Handle:
The forward pass correctly increments each child's candy count sequentially from one upwards.
Strictly monotonically decreasing ratings
How to Handle:
The backward pass correctly ensures each child gets strictly more candies than their right neighbor from the end.
V-shaped ratings where the lowest rating is in the middle
How to Handle:
The combination of left-to-right and right-to-left passes correctly takes the maximum of both directional requirements at the lowest point.
Extremely large rating values
How to Handle:
Using standard integer accumulators for the total candy count prevents overflow since sums scale linearly with array length rather than rating magnitude.
0/75 completed