Distribute Candies to People - Problem

We distribute some number of candies to a row of n = num_people people in the following way:

We give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.

Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.

This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.

The last person will receive all of our remaining candies (not necessarily one more than the previous gift).

Return an array (of length num_people and sum candies) that represents the final distribution of candies.

Input & Output

Example 1 — Basic Distribution
$ Input: candies = 7, num_people = 4
Output: [1,2,1,1]
💡 Note: Round 1: Give 1,2,3,1 to people 0,1,2,3. After person 2 gets 3, only 1 candy left, so person 3 gets 1 instead of 4.
Example 2 — Multiple Rounds
$ Input: candies = 10, num_people = 3
Output: [5,2,3]
💡 Note: Round 1: Give 1,2,3 to people 0,1,2. Round 2: Give 4 to person 0. Total: [1+4, 2, 3] = [5,2,3]
Example 3 — Exact Distribution
$ Input: candies = 10, num_people = 4
Output: [1,2,3,4]
💡 Note: One complete round: Give 1,2,3,4 to people 0,1,2,3. Total candies used: 1+2+3+4 = 10, exactly matches.

Constraints

  • 1 ≤ candies ≤ 109
  • 1 ≤ num_people ≤ 1000

Visualization

Tap to expand
Distribute 7 Candies to 4 PeopleInput:7Total CandiesDistribution Process:1231Person 0Person 1Person 2Person 3Only 1 candy left when reaching Person 3Output: [1,2,1,1]Total distributed: 1+2+1+1 = 5... wait, that's wrong!
Understanding the Visualization
1
Input
7 candies to distribute among 4 people
2
Process
Give 1,2,3,1 candies (running out after giving 3)
3
Output
Final distribution [1,2,1,1]
Key Takeaway
🎯 Key Insight: Track current candy amount and person position, distribute until candies run out
Asked in
Amazon 15 Google 10
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen