Distribute Candies to People — LeetCode 1103 Python Solution

EasyMathSimulation
Problem
#1103
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(\max(\sqrt{candies}, num\_people))
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview