Magicsheet logo

Distribute Candies to People

Easy
12.5%
Updated 8/1/2025

Asked by 1 Company

Distribute Candies to People

What is this problem about?

In the Distribute Candies to People coding problem, you have a certain number of candies and a row of nn people. You give 1 candy to the first person, 2 to the second, and so on until the nn-th person gets nn candies. Then you return to the first person and give n+1n+1 candies, n+2n+2 to the second, etc. This continues until you run out of candies. The last person receives whatever is left. You need to return an array showing the total candies each person received.

Why is this asked in interviews?

Amazon uses this question to test basic Simulation interview patterns and loop control. It evaluations whether you can handle a process that "wraps around" an array and correctly manages a depleting resource. It also tests your ability to handle arithmetic progressions and ensure that the final "leftover" distribution is handled accurately.

Algorithmic pattern used

This is a Simulation problem.

  1. Initialize an array of size nn with zeros.
  2. Use a counter give = 1 and an index i = 0.
  3. While candies > 0:
    • Calculate how much to give: actualGive = min(give, candies).
    • Add actualGive to result[i % n].
    • Subtract actualGive from candies.
    • Increment give and i. The time complexity is O(candies)O(\sqrt{candies}) because the number of candies given grows linearly, meaning the loop runs roughly 2×candies\sqrt{2 \times candies} times.

Example explanation

Candies = 7, People = 4.

  1. Person 0: Give 1. Left = 6. Result: [1, 0, 0, 0].
  2. Person 1: Give 2. Left = 4. Result: [1, 2, 0, 0].
  3. Person 2: Give 3. Left = 1. Result: [1, 2, 3, 0].
  4. Person 3: Give 4. Only 1 left. Give 1. Result: [1, 2, 3, 1]. Final Result: [1, 2, 3, 1].

Common mistakes candidates make

  • Modulo arithmetic: Forgetting to use i % n to wrap back to the first person.
  • Last person logic: Subtracting give from candies even if candies < give, resulting in a negative candy count.
  • Loop termination: Not checking the condition inside the loop correctly.

Interview preparation tip

When a problem involves "rounds" or "repeated passes" over an array, the modulo operator (%) is your best friend. It allows you to treat a linear array as a circular one without complex resetting logic.

Similar Questions