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
Distribute 3 Candies into 2 Non-Empty Bags1233 Unique CandiesWay 1:123Way 2:213Way 3:312Each way: both bags must be non-emptyBag order doesn't matter: (1),(2,3) same as (2,3),(1)Total: 3 different ways
Understanding the Visualization
1
Input
n=3 unique candies, k=2 bags
2
Partition
Find all ways to split candies into 2 non-empty groups
3
Count
Total valid distributions = 3
Key Takeaway
🎯 Key Insight: This is computing Stirling numbers S(n,k) using dynamic programming with recurrence S(n,k) = k×S(n-1,k) + S(n-1,k-1)
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