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 Candies to People INPUT 7 Candies 4 People in a Row: P1 P2 P3 P4 candies = 7 num_people = 4 ALGORITHM STEPS 1 Initialize result = [0,0,0,0], give=1 2 Round 1: Give 1,2,3,4 P1:1, P2:2, P3:3, P4:4 Distribution Process: Round 1: 1+2+3 = 6 (need 10) P1:+1, P2:+2, P3:+3 Remaining: 7-6 = 1 P4 gets only 1 (not 4) 3 Handle Remainder Last gets min(need, left) 4 Return Result Final: [1,2,3,1]-->[1,2,3,1] Time: O(sqrt(candies)) Space: O(num_people) FINAL RESULT 1 2 3 1 Output Array: 1 2 3 1 Verification: 1+2+3+1 = 7 -- OK P4 expected 4, got only 1 (remaining candies) Key Insight: The optimal approach simulates distribution while tracking position using modulo (i % n). Each iteration gives (turn+1) candies to person at (turn % n). When candies run low, give remaining. Total distributions ~ sqrt(2*candies), making this efficient: O(sqrt(candies)) time complexity. TutorialsPoint - Distribute Candies to People | Optimal Solution
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