Distribute Candies to People — LeetCode 1103 Python Solution
- Problem
- #1103
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
We distribute some number of candies, to a row of n = num_people people in the following way: We then 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.
Example
- Input
- candies = 7, num_people = 4
- Output
- [1,2,3,1]
- Explanation
- On the first turn, ans[0] += 1, and the array is [1,0,0,0].
Python solution
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
ans = [0] * num_people
i = 0
while candies:
ans[i % num_people] += min(candies, i + 1)
candies -= min(candies, i + 1)
i += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\max(\sqrt{candies}, num\_people)) |
| Space | O(num\_people) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1103. Distribute Candies to People is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1103. Distribute Candies to People?
- LeetCode 1103. Distribute Candies to People is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1103. Distribute Candies to People?
- The Python solution on this page runs in O(\max(\sqrt{candies}, num\_people)).
- What is the space complexity of LeetCode 1103. Distribute Candies to People?
- The Python solution on this page uses O(num\_people) auxiliary space.
- What topics does LeetCode 1103. Distribute Candies to People cover?
- LeetCode 1103. Distribute Candies to People is tagged Math and Simulation on LeetCode.