Skip to main content

Distribute Candies Among Children II - Solution & Explanation

MediumMathCombinatoricsEnumeration20 min readAsked at: Amazon, Meta, Google +2
Practice this problem

Problem Statement

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 1:

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).

Example 2:

Input: n = 3, limit = 3
Output: 10
Explanation: There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (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) and (3, 0, 0).

 

Constraints:

  • 1 <= n <= 106
  • 1 <= limit <= 106

Approach Overview

Problem Overview: You are given n candies and three children. Each child can receive between 0 and limit candies. The task is to count how many distributions (a, b, c) satisfy a + b + c = n while keeping every value ≤ limit. This turns into a counting problem over constrained integer triples, which falls under math and combinatorics.

Approach 1: Brute Force Using Nested Loops (Time: O(limit2), Space: O(1))

Enumerate all possible values for the first two children. Use two nested loops where a ranges from 0 to limit and b ranges from 0 to limit. For each pair, compute c = n - a - b. If 0 ≤ c ≤ limit, the distribution is valid and you increment the count. This works because once two values are fixed, the third is uniquely determined by the sum constraint. The method is simple and easy to reason about, making it a good baseline when first approaching enumeration problems.

Approach 2: Dynamic Programming Counting (Time: O(n × limit), Space: O(n))

Dynamic programming treats the problem as distributing candies child by child. Define dp[i] as the number of ways to distribute exactly i candies among the processed children. Start with dp[0] = 1. For each child, build a new DP array where you try giving that child 0..limit candies and accumulate the number of ways to reach each sum. The transition is new_dp[s + k] += dp[s] for every valid k from 0 to limit. After processing all three children, the answer is dp[n]. This converts the triple enumeration into structured state transitions and avoids explicitly checking every pair combination.

The DP formulation generalizes well. If the number of children increases or limits vary per child, the same idea still works with minimal changes. It also illustrates how counting problems with constraints can be modeled with dynamic programming instead of direct iteration.

Recommended for interviews: Start with the nested loop enumeration. It shows you understand the constraint a + b + c = n and how fixing two variables determines the third. Then discuss the DP counting formulation as the scalable approach. Strong candidates often also mention the combinatorics insight: the problem can be solved with inclusion–exclusion in O(1) time using counting formulas.

Approach 1: Brute Force Using Nested Loops

This approach uses three nested loops to iterate over all possible distributions of candies to check each combination of candies for three children. This method directly checks if each combination satisfies the condition and counts the valid distributions.

This C program uses three nested loops to iterate through all possible values each child can receive up to limit. It checks the remaining candies for the third child, ensuring they are also within the limit.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(limit^2)
Space Complexity: O(1)

Try this approach in the editor →

Approach 2: Dynamic Programming

Using dynamic programming, we can optimize the solution. We create a 3D DP array dp[i][j][k] where i, j, and k are the numbers of candies given to each child such that they collectively add up to n. Given constraints, we can fill the DP array by considering the subproblems of distributing fewer candies.

This C program initializes a DP table, filling valid entries based on the number of candies given to each child meeting the limit condition. The DP approach allows for efficient counting of valid distributions without recalculating repeated subproblems.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(limit^2)
Space Complexity: O(limit^2)

Try this approach in the editor →

Approach 3: Combinatorial Mathematics + Principle of Inclusion-Exclusion

According to the problem description, we need to distribute n candies to 3 children, with each child receiving between [0, limit] candies.

This is equivalent to placing n balls into 3 boxes. Since the boxes can be empty, we can add 3 virtual balls, and then use the method of inserting partitions, i.e., there are a total of n + 3 balls, and we insert 2 partitions among the n + 3 - 1 positions, thus dividing the actual n balls into 3 groups, and allowing the boxes to be empty. Therefore, the initial number of schemes is C_{n + 2}^2.

We need to exclude the schemes where the number of balls in a box exceeds limit. Consider that there is a box where the number of balls exceeds limit, then the remaining balls (including virtual balls) have at most n + 3 - (limit + 1) = n - limit + 2, and the number of positions is n - limit + 1, so the number of schemes is C_{n - limit + 1}^2. Since there are 3 boxes, the number of such schemes is 3 times C_{n - limit + 1}^2. In this way, we will exclude too many schemes where the number of balls in two boxes exceeds limit at the same time, so we need to add the number of such schemes, i.e., 3 times C_{n - 2 times limit}^2.

The time complexity is O(1), and the space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Brute Force Using Nested Loops

Time Complexity: O(limit^2)
Space Complexity: O(1)

Dynamic Programming

Time Complexity: O(limit^2)
Space Complexity: O(limit^2)

Combinatorial Mathematics + Principle of Inclusion-Exclusion

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Using Nested LoopsO(limit²)O(1)Best for understanding the constraint a + b + c = n and when limits are small.
Dynamic Programming CountingO(n × limit)O(n)Preferred when the number of children or constraints increase and brute force enumeration becomes harder to manage.

Video Solution

Distribute Candies Among Children II | 4 Approaches | Detailed | Leetcode 2929 | codestorywithMIKcodestorywithMIK13,751 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Distribute Candies Among Children II easy or hard?
The problem is rated Medium on LeetCode. The brute force enumeration is straightforward, but recognizing the combinatorics structure or designing a scalable counting approach is what elevates the difficulty.
Distribute Candies Among Children II Python/Java solution
Typical implementations iterate over possible values for two children and compute the third value directly. Python, Java, C++, and similar languages can implement this in a few lines using nested loops and a validity check for the remaining candies.
How to solve Distribute Candies Among Children II in O(n)?
An even faster solution comes from combinatorics. First count all non‑negative solutions to a + b + c = n using combinations, then subtract cases where any child exceeds the limit using inclusion–exclusion. This converts the counting problem into a few constant‑time arithmetic operations, resulting in O(1) time.
What is the best approach for Distribute Candies Among Children II?
The most practical implementation approach is enumeration with constraints or dynamic programming counting. The brute force method fixes two variables and derives the third, giving O(limit^2) time and O(1) space. For more scalable variants, a DP counting approach with O(n × limit) time works well. Many advanced solutions also derive an O(1) combinatorics formula using inclusion–exclusion.
Is Distribute Candies Among Children II asked at Google/Amazon/Meta?
Problems involving constrained distributions and counting combinations appear frequently in interviews at companies like Google, Amazon, and Meta. Variants often test combinatorics reasoning, inclusion–exclusion, or dynamic programming for counting valid states.
What data structure is used in Distribute Candies Among Children II?
The brute force solution uses simple iteration with no additional data structures. The dynamic programming approach uses a one‑dimensional array where dp[i] stores the number of ways to form i candies after processing some children.
What is the time complexity of Distribute Candies Among Children II?
The straightforward nested loop enumeration runs in O(limit^2) time because two children are iterated explicitly while the third value is computed. A dynamic programming solution runs in O(n × limit) time by building ways to reach each candy sum. Space complexity is O(1) for brute force and O(n) for DP.

Ready to solve this problem?

Practice Distribute Candies Among Children II with our built-in code editor and test cases.

Practice on FleetCode