Distribute Candies to People - Problem
Imagine you're a teacher with a bag of candies to distribute to your students in a fun, systematic way! 🍭
You have candies number of candies and num_people students sitting in a row. You'll distribute candies in rounds, following this pattern:
- Round 1: Give 1 candy to person 1, 2 candies to person 2, ..., n candies to person n
- Round 2: Give (n+1) candies to person 1, (n+2) candies to person 2, ..., 2n candies to person n
- Round 3: Continue the pattern...
Keep going until you run out of candies. If you don't have enough candies for the next person's full amount, give them all remaining candies.
Goal: Return an array showing how many candies each person received in total.
Input & Output
example_1.py — Basic Distribution
$
Input:
candies = 7, num_people = 4
›
Output:
[1, 2, 3, 1]
💡 Note:
Round 1: Person 1 gets 1 candy, Person 2 gets 2 candies, Person 3 gets 3 candies. We've used 6 candies. Round 2: Person 4 should get 4 candies, but we only have 1 left, so Person 4 gets 1 candy.
example_2.py — Multiple Complete Rounds
$
Input:
candies = 10, num_people = 3
›
Output:
[5, 2, 3]
💡 Note:
Round 1: [1, 2, 3] - used 6 candies. Round 2: Person 1 should get 4 more, but we only have 4 candies left, so Person 1 gets 4. Final totals: [1+4, 2+0, 3+0] = [5, 2, 3]
example_3.py — Exact Match
$
Input:
candies = 6, num_people = 3
›
Output:
[1, 2, 3]
💡 Note:
Perfect! We have exactly enough candies for one complete round: 1+2+3 = 6 candies total.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
People sit in a circle, you start with a bag of candies
2
Round 1
Give 1 candy to person 1, 2 to person 2, etc.
3
Round 2
Continue from where you left off: person 1 gets next amount
4
Final
When candies run low, last person gets whatever remains
Key Takeaway
🎯 Key Insight: Use modular arithmetic to cycle through people efficiently. The simulation approach works well because num_people ≤ 1000, making the circular iteration manageable even for large candy counts.
Time & Space Complexity
Time Complexity
O(√candies)
We distribute candies in increasing amounts (1,2,3...), so we need roughly √candies iterations
✓ Linear Growth
Space Complexity
O(num_people)
Only need space for the result array of size num_people
⚡ Linearithmic Space
Constraints
- 1 ≤ candies ≤ 109
- 1 ≤ num_people ≤ 1000
- Note: The number of candies can be very large, but number of people is limited
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code