Count Ways to Distribute Candies - Problem

Imagine you're organizing a candy distribution event where you need to divide n unique candies (labeled 1 through n) into k bags such that every bag contains at least one candy.

The challenge is to count how many different ways you can accomplish this distribution. Two distributions are considered different if there exists at least one pair of candies that are together in one distribution but separated in another.

Key Rules:

  • Every bag must contain at least one candy
  • The order of bags doesn't matter: (1), (2,3)(2,3), (1)
  • The order within bags doesn't matter: (2,3)(3,2)
  • But groupings matter: (1), (2,3)(1,2), (3)

Example: With candies [1,2,3] and 2 bags, valid distributions are: (1), (2,3), (2), (1,3), and (3), (1,2) — that's 3 ways total.

Return the result modulo 109 + 7 as the answer can be very large.

Input & Output

example_1.py — Basic Case
$ Input: n = 3, k = 2
Output: 3
💡 Note: With 3 candies and 2 bags, we can distribute as: (1),(2,3) or (2),(1,3) or (3),(1,2). That's 3 different ways.
example_2.py — Equal Distribution
$ Input: n = 4, k = 4
Output: 1
💡 Note: With 4 candies and 4 bags, there's only one way: each candy goes in its own bag (1),(2),(3),(4).
example_3.py — Impossible Case
$ Input: n = 2, k = 3
Output: 0
💡 Note: Cannot distribute 2 candies into 3 non-empty bags - it's impossible, so return 0.

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ k ≤ 1000
  • Answer fits in 32-bit signed integer after taking modulo 109 + 7

Visualization

Tap to expand
Candy Distribution Visualizationn=4 candies, k=2 bags12344 Unique CandiesAll Possible Ways (S(4,2) = 7):{1} | {2,3,4}{2} | {1,3,4}{3} | {1,2,4}{4} | {1,2,3}{1,2} | {3,4}{1,3} | {2,4}{1,4} | {2,3}DP Recurrence: S(4,2) = 2×S(3,2) + S(3,1) = 2×3 + 1 = 7Key InsightEach candy can either:1. Join one of k existing bags: k×S(n-1,k)2. Start a new bag: S(n-1,k-1)
Understanding the Visualization
1
Identify the Pattern
This is counting set partitions - Stirling numbers of second kind S(n,k)
2
Set Up Recurrence
S(n,k) = k×S(n-1,k) + S(n-1,k-1) - either join existing group or form new one
3
Build DP Table
Fill table bottom-up using base cases and recurrence relation
4
Return Answer
S(n,k) gives the exact count we need, modulo 10^9+7
Key Takeaway
🎯 Key Insight: This is a classic application of Stirling numbers of the second kind, solved efficiently with dynamic programming in O(n×k) time.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
21.4K Views
Medium Frequency
~25 min Avg. Time
892 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