The Count Ways to Distribute Candies interview question asks you to find the number of ways to distribute unique candies into identical bags such that each bag contains at least one candy. This is a classic combinatorial problem involving the distribution of distinct objects into identical bins.
Google uses this Dynamic Programming interview pattern to see if a candidate can recognize and solve a problem that maps to "Stirling numbers of the second kind." It tests your ability to derive recurrence relations for distribution problems and optimize them using DP to avoid exponential time complexity.
This problem is solved using 2D Dynamic Programming.
Let dp[i][j] be the number of ways to distribute unique candies into identical bags.
dp[i][i] = 1 (one candy per bag), and dp[i][1] = 1 (all candies in one bag).dp[i-1][j-1] ways.j * dp[i-1][j] ways.dp[i][j] = dp[i-1][j-1] + j * dp[i-1][j].Distribute 3 unique candies (A, B, C) into 2 identical bags.
{A, B}, {C}.{A}, {B}.{A, C}, {B}.{A}, {B, C}.
Total ways = 1 + 2 = 3.Practice identifying the difference between "labeled" and "unlabeled" objects/containers. This distinction changes the problem from simple powers or factorials to partitions and Stirling numbers.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Ways to Stay in the Same Place After Some Steps | Hard | Solve | |
| Student Attendance Record II | Hard | Solve | |
| Race Car | Hard | Solve | |
| K Inverse Pairs Array | Hard | Solve | |
| Painting a Grid With Three Different Colors | Hard | Solve |