Skip to main content

Count Ways to Distribute Candies - Solution & Explanation

HardPremiumFree on FleetCodeDynamic Programming8 min readAsked at: Google
Practice this problem

Problem Statement

There are n unique candies (labeled 1 through n) and k bags. You are asked to distribute all the candies into the bags such that every bag has at least one candy.

There can be multiple ways to distribute the candies. Two ways are considered different if the candies in one bag in the first way are not all in the same bag in the second way. The order of the bags and the order of the candies within each bag do not matter.

For example, (1), (2,3) and (2), (1,3) are considered different because candies 2 and 3 in the bag (2,3) in the first way are not in the same bag in the second way (they are split between the bags (2) and (1,3)). However, (1), (2,3) and (3,2), (1) are considered the same because the candies in each bag are all in the same bags in both ways.

Given two integers, n and k, return the number of different ways to distribute the candies. As the answer may be too large, return it modulo 109 + 7.

 

Example 1:

Input: n = 3, k = 2
Output: 3
Explanation: You can distribute 3 candies into 2 bags in 3 ways:
(1), (2,3)
(1,2), (3)
(1,3), (2)

Example 2:

Input: n = 4, k = 2
Output: 7
Explanation: You can distribute 4 candies into 2 bags in 7 ways:
(1), (2,3,4)
(1,2), (3,4)
(1,3), (2,4)
(1,4), (2,3)
(1,2,3), (4)
(1,2,4), (3)
(1,3,4), (2)

Example 3:

Input: n = 20, k = 5
Output: 206085257
Explanation: You can distribute 20 candies into 5 bags in 1881780996 ways. 1881780996 modulo 109 + 7 = 206085257.

 

Constraints:

  • 1 <= k <= n <= 1000

Approach Overview

Problem Overview: You have n candies and k children. Each child must receive at least one candy. The task is to count how many distinct ways you can distribute the candies while satisfying this constraint. The result is returned modulo 1e9 + 7.

Approach 1: Recursive Enumeration (Exponential Time)

The most direct idea is to try every possible assignment of candies to children while ensuring every child receives at least one. A recursive function decides whether the current candy starts a new group or joins an existing one. This brute-force exploration quickly explodes because every candy can branch into multiple placements. The time complexity is exponential O(k^n) and the recursion stack uses O(n) space. This approach mainly helps you understand the structure of the recurrence before applying dynamic programming.

Approach 2: 2D Dynamic Programming (O(nk) time, O(nk) space)

Define dp[i][j] as the number of ways to distribute i candies among j children so that every child has at least one candy. When adding the i‑th candy, two choices exist. Start a new group for a child who previously had none (dp[i-1][j-1]) or give the candy to one of the j children who already has candies (j * dp[i-1][j]). The recurrence becomes dp[i][j] = dp[i-1][j-1] + j * dp[i-1][j]. Iterate i from 1 to n and j from 1 to k. This recurrence is closely related to Stirling numbers of the second kind from combinatorics. Time complexity is O(nk) and space complexity is O(nk).

Approach 3: Space Optimized Dynamic Programming (O(nk) time, O(k) space)

The DP transition only depends on the previous row i-1. You can compress the table into a single 1D array where dp[j] represents ways for the current candy count. Iterate candies one by one and update children counts from k down to 1 so previous values are not overwritten. Apply the same transition dp[j] = dp[j-1] + j * dp[j] (modulo 1e9+7). This keeps the time complexity O(nk) but reduces space to O(k). This version is usually preferred in interviews because it shows mastery of DP state transitions and memory optimization.

Recommended for interviews: The 2D DP clearly demonstrates the recurrence and is the easiest way to explain the reasoning. After presenting it, reduce space to a 1D DP array to show optimization skills. Interviewers typically expect the O(nk) dynamic programming solution with the recurrence dp[i][j] = dp[i-1][j-1] + j * dp[i-1][j].

Solution

We define f[i][j] as the number of different ways to distribute i candies to j bags. Initially, f[0][0]=1, and the answer is f[n][k].

We consider how to distribute the i-th candy. If the i-th candy is distributed to a new bag, then f[i][j]=f[i-1][j-1]. If the i-th candy is distributed to an existing bag, then f[i][j]=f[i-1][j]times j. Therefore, the state transition equation is:

$ f[i][j]=f[i-1][j-1]+f[i-1][j]times j

The final answer is f[n][k].

The time complexity is O(n times k), and the space complexity is O(n times k). Here, n and k$ are the number of candies and bags, respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor β†’

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive EnumerationO(k^n)O(n)Conceptual understanding of the recurrence before optimization
2D Dynamic ProgrammingO(nk)O(nk)Clear implementation and easiest to explain during interviews
1D Space Optimized DPO(nk)O(k)When memory matters or when optimizing the DP transition

Video Solution

Leetcode 1692. Count Ways to Distribute Candies β€’ Fearless Learner β€’ 334 views views

Watch 1 more video solutions β†’

Frequently Asked Questions

Is Count Ways to Distribute Candies easy or hard?
LeetCode classifies this problem as Hard because it requires recognizing a combinatorial DP recurrence. Once the DP state and transition are identified, the implementation itself is straightforward.
Count Ways to Distribute Candies Python/Java solution
Implement the DP recurrence dp[i][j] = dp[i-1][j-1] + j * dp[i-1][j] with modulo 1e9+7. The algorithm works the same across Python, Java, C++, Go, and TypeScript with time complexity O(nk) and optional space optimization to O(k).
How to solve Count Ways to Distribute Candies in O(nk)?
Define dp[i][j] as the number of ways to distribute i candies among j children. When adding the i-th candy, either create a new group (dp[i-1][j-1]) or give it to one of the j existing children (j * dp[i-1][j]). Iterating over all i and j produces the final answer dp[n][k] in O(nk) time.
What is the best approach for Count Ways to Distribute Candies?
The standard solution uses dynamic programming with the recurrence dp[i][j] = dp[i-1][j-1] + j * dp[i-1][j]. It counts ways to distribute i candies among j children where each child gets at least one. This approach runs in O(nk) time and can be optimized to O(k) space.
Is Count Ways to Distribute Candies asked at Google/Amazon/Meta?
This type of combinatorics and dynamic programming problem appears in interviews at large tech companies including Google, Amazon, and Meta. Variations often test understanding of DP state transitions and counting techniques such as Stirling numbers.
What data structure is used in Count Ways to Distribute Candies?
The core structure is a dynamic programming array. Most implementations use a 2D DP table dp[n+1][k+1], while optimized solutions reduce it to a 1D array of size k+1 to save memory.
What is the time complexity of Count Ways to Distribute Candies?
The optimal dynamic programming solution runs in O(nk) time where n is the number of candies and k is the number of children. Each DP state is computed once using constant-time transitions. Space complexity is O(nk) for the full table or O(k) with space optimization.

Ready to solve this problem?

Practice Count Ways to Distribute Candies with our built-in code editor and test cases.

Practice on FleetCode