Distribute Candies Among Children I - Problem

Imagine you're a parent with n candies that you want to distribute fairly among your 3 children. However, you have a rule: no single child can receive more than limit candies to ensure fairness and prevent sugar overload! 🍬

Your task is to find the total number of ways to distribute all n candies among the 3 children such that:

  • Each child can receive 0 or more candies
  • No child receives more than limit candies
  • All n candies must be distributed

Example: If you have 5 candies and limit is 2, one valid distribution is [2, 2, 1] - giving 2 candies to the first child, 2 to the second, and 1 to the third.

Input & Output

example_1.py — Basic Distribution
$ Input: n = 5, limit = 2
Output: 3
💡 Note: The valid distributions are: [1,2,2], [2,1,2], [2,2,1]. Each child gets at most 2 candies and all 5 candies are distributed.
example_2.py — High Limit
$ Input: n = 3, limit = 3
Output: 10
💡 Note: Since limit ≥ n, any distribution is valid. This includes [0,0,3], [0,1,2], [0,2,1], [0,3,0], [1,0,2], [1,1,1], [1,2,0], [2,0,1], [2,1,0], [3,0,0].
example_3.py — Edge Case
$ Input: n = 1, limit = 1
Output: 3
💡 Note: The valid distributions are: [0,0,1], [0,1,0], [1,0,0]. Only one child gets the single candy in each case.

Visualization

Tap to expand
Candy Distribution Among 3 ChildrenChild 10 to limitChild 20 to remainingChild 3n - c1 - c2n candiesAlgorithm Steps1. For child1 = 0 to min(n, limit):2. For child2 = 0 to min(n - child1, limit):3. child3 = n - child1 - child24. If 0 ≤ child3 ≤ limit: count++5. Return countTime Complexity: O(limit²), Space Complexity: O(1)
Understanding the Visualization
1
Setup
We have n total candies and each child can get at most 'limit' candies
2
Enumerate Child 1
Try giving 0 to min(n, limit) candies to the first child
3
Enumerate Child 2
For each Child 1 allocation, try all valid amounts for Child 2
4
Calculate Child 3
The remaining candies automatically go to Child 3
5
Validate
Count only if Child 3's allocation is within the limit
Key Takeaway
🎯 Key Insight: By fixing the first two children's candy counts, the third child's count is automatically determined, making this an efficient O(limit²) enumeration problem.

Time & Space Complexity

Time Complexity
⏱️
O(limit²)

We have two nested loops, each running up to 'limit' times

n
2n
Linear Growth
Space Complexity
O(1)

Only using a few variables to track counts and iterations

n
2n
Linear Space

Constraints

  • 1 ≤ n ≤ 50
  • 1 ≤ limit ≤ 50
  • All inputs are positive integers
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
12.8K Views
Medium Frequency
~8 min Avg. Time
340 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen