Python 1103.py
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
# brute force
result = [ 0 ] * num_people
step = 0
while candies > 0:
pos = step % num_people
step += 1
give = min(step, candies)
result[pos] += give
candies -= give
return result
Difficulty
and has an acceptance rate of about 68% (100k+ submissions).
Typical patterns to solve this problem:
- Math
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “candies distribution” problem: given a total number of candies and a fixed number of people, it distributes the candies in rounds where the i-th round gives i candies to the next person in line. The algorithm continues until all candies are exhausted and returns a list indicating how many candies each person received.
Core Logic
The function begins by allocating a result list sized to the number of people, each entry initialized to zero. This is achieved with list multiplication, which creates the list in a single operation and avoids repeated appends.
result = [0] * num_people
A variable step tracks the current round number. The loop runs while there are still candies left. Inside the loop, the position of the current recipient is computed using the modulo operator, which wraps the index back to the start after reaching the last person.
pos = step % num_people
step += 1
The amount to give in the current round is the smaller of the round number (step) and the remaining candies. The min function handles the situation where the remaining candies are insufficient for a full round, ensuring that no more candies are taken than are available.
give = min(step, candies)
The recipient’s total is updated, and the remaining candy count is reduced accordingly.
result[pos] += give
candies -= give
When the loop exits, the fully populated result list is returned.
return result
Edge Cases Handled
When the initial candy count is zero, the while condition fails immediately, and the function returns a list of zeros, correctly representing that no one received any candies.
If the total number of candies is smaller than the number of people, the modulo calculation still yields a valid index, and the min call ensures that only the available candies are given in the first round, leaving the rest of the list unchanged.
For very large values of candies or num_people, the algorithm continues to operate correctly because the loop condition and arithmetic operations are based on integer arithmetic without overflow concerns in Python’s arbitrary-precision integers.
Performance Optimizations
The code avoids unnecessary data structures; the result list is allocated once and updated in place, eliminating the overhead of dynamic resizing.
Using the modulo operator to compute the recipient’s index eliminates the need for an explicit pointer that must be reset after each full cycle, keeping the index calculation O(1) per iteration.
The min function replaces a conditional branch that would otherwise compare step and candies manually, resulting in a concise and efficient determination of the actual amount to distribute.
By decrementing candies directly with the amount given, the loop’s termination condition is evaluated against a single variable, avoiding extra bookkeeping.
Overall, the implementation leverages Python’s built-in operations to keep each iteration lightweight, which translates to fast execution even when the number of iterations grows large.
ELI5 - Simplified Explanation
Imagine a row of children standing in a line waiting for treats. The code starts by setting up a little box for each child, and at the beginning, every box is completely empty. There is also a big pile of candies that needs to be shared among everyone.
To hand out the treats, the process goes down the line one child at a time. The first child gets one candy, then the next child gets two candies, then the next gets three, and this continues, giving more and more with each turn. If the person at the end of the line gets their turn, the next person to receive treats starts back over at the beginning of the line again.
Every time a child gets a turn, the code looks at how many candies are left in the pile. If there are enough, the child gets their share. If the pile is running low and does not have as many as the turn requires, the child just takes whatever is left in the pile until there are no candies remaining. The numbers in the boxes keep track of how many treats each child collected throughout the entire game until every last candy is gone.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1122: Relative Sort Array
- problem 1160: Find Words That Can Be Formed by Characters
- problem 1080: Insufficient Nodes in Root to Leaf Paths
- problem 1138: Alphabet Board Path
- problem 1162: As Far from Land as Possible
- problem 1921: Eliminate Maximum Number of Monsters
- problem 1178: Number of Valid Words for Each Puzzle
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality