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

Distribute Candies to People

Number: 1195

Difficulty: Easy

Paid? No

Companies: Amazon


Problem Description

Given a number of candies and a number of people, distribute the candies in a sequential manner: the first person gets 1 candy, the second gets 2, and so on until the last person. Then, the distribution resumes from the first person with the next increasing number of candies. Continue the process until all candies have been distributed. If the remaining candies are less than the expected amount for a turn, give all the remaining candies to the person in turn.


Key Insights

  • Use an array to represent the candy count for each person.
  • Distribute candies in rounds, where the amount given increases by 1 each time.
  • Use modulo arithmetic to cycle through the people.
  • In the final round, if the remaining candies are less than expected, give the remainder.

Space and Time Complexity

Time Complexity: O(√candies) — The number of iterations is proportional to the number of candies distributed, which increases roughly as the square root of the total candies. Space Complexity: O(num_people) — Only an array of size num_people is required.


Solution

We simulate the distribution process using a loop. We maintain a result list of length num_people initialized with zero. Starting from the first person, we distribute an incrementally increasing number of candies. For each turn, we calculate the amount to give (which is the current count or the remaining candies if less). We then update the corresponding position in the result array, decrease the total candy count, increment the candy value by one, and use modulo arithmetic to move to the next person. The process stops when we have no more candies to distribute.


Code Solutions

def distributeCandies(candies, num_people):
    # Initialize the result list with zeros for each person.
    distribution = [0] * num_people
    
    # Start with the first candy quantity.
    candy_to_give = 1
    index = 0
    
    # Continue until all candies are distributed.
    while candies > 0:
        # Determine the number of candies to distribute in this turn.
        current_candies = min(candy_to_give, candies)
        
        # Add candies to the current person.
        distribution[index] += current_candies
        
        # Subtract the distributed candies from total.
        candies -= current_candies
        
        # Move to the next candy amount and person (cycling via modulo).
        candy_to_give += 1
        index = (index + 1) % num_people
        
    return distribution

# Example usage:
print(distributeCandies(7, 4))  # Output: [1,2,3,1]
← Back to All Questions