Count Ways to Distribute Candies - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 2
Output: 3
💡 Note: 3 ways to distribute 3 candies into 2 non-empty bags: (1),(2,3) or (2),(1,3) or (3),(1,2)
Example 2 — Equal Partitions
$ Input: n = 2, k = 1
Output: 1
💡 Note: Only 1 way: put both candies (1,2) in the single bag
Example 3 — Each in Own Bag
$ Input: n = 4, k = 4
Output: 1
💡 Note: Only 1 way: each candy goes in its own bag (1),(2),(3),(4)

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ k ≤ 1000
  • Answer modulo 109 + 7

Visualization

Tap to expand
Count Ways to Distribute Candies INPUT n = 3 unique candies 1 2 3 k = 2 bags Bag A Bag B n = 3 (candies) k = 2 (bags) ALGORITHM STEPS 1 Stirling Numbers S(n,k) = partitions of n items into k groups 2 Recurrence Relation S(n,k) = k*S(n-1,k) + S(n-1,k-1) 3 Build DP Table Base: S(n,1)=1, S(n,n)=1 n\k 1 2 3 1 1 - - 2 1 1 - 3 1 3 1 4 Return Result S(3,2) = 2*S(2,2)+S(2,1) = 2*1 + 1 = 3 FINAL RESULT 3 Valid Distributions: Way 1: 1 | 2 3 {1} {2,3} Way 2: 2 | 1 3 {2} {1,3} Way 3: 3 | 1 2 {3} {1,2} Output: 3 Key Insight: This problem uses Stirling Numbers of the Second Kind S(n,k). The recurrence S(n,k) = k*S(n-1,k) + S(n-1,k-1) means: either add candy n to one of k existing groups (k ways), or create a new group with candy n. Time: O(n*k) | Space: O(n*k) for DP table. Use modulo 10^9+7 for large results. TutorialsPoint - Count Ways to Distribute Candies | Optimal Solution (Stirling Numbers DP)
Asked in
Google 25 Amazon 18 Microsoft 15
23.5K Views
Medium Frequency
~25 min Avg. Time
890 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