Distribute Candies Among Children I — LeetCode 2928 Python Solution

EasyMathCombinatoricsEnumeration
Problem
#2928
Reading time
2 min

The problem

You are given two positive integers n and limit. Return the total number of ways to distribute n candies among 3 children such that no child gets more than limit candies.

Example

Input
n = 5, limit = 2
Output
3
Explanation
There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).

Python solution

Python
class Solution:
    def distributeCandies(self, n: int, limit: int) -> int:
        if n > 3 * limit:
            return 0
        ans = comb(n + 2, 2)
        if n > limit:
            ans -= 3 * comb(n - limit + 1, 2)
        if n - 2 >= 2 * limit:
            ans += 3 * comb(n - 2 * limit, 2)
        return ans

Complexity

MeasureComplexity
TimeO(1)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2928. Distribute Candies Among Children I is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Combinatorics.

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 2928. Distribute Candies Among Children I?
LeetCode 2928. Distribute Candies Among Children I is rated Easy on LeetCode.
What is the time complexity of LeetCode 2928. Distribute Candies Among Children I?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 2928. Distribute Candies Among Children I?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2928. Distribute Candies Among Children I cover?
LeetCode 2928. Distribute Candies Among Children I is tagged Math, Combinatorics and Enumeration 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