Count Ways to Distribute Candies — LeetCode 1692 Python Solution

HardLeetCode PremiumDynamic Programming
Problem
#1692
Reading time
2 min

The 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.

Example

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

Python solution

Python
class Solution:
    def waysToDistribute(self, n: int, k: int) -> int:
        mod = 10**9 + 7
        f = [[0] * (k + 1) for _ in range(n + 1)]
        f[0][0] = 1
        for i in range(1, n + 1):
            for j in range(1, k + 1):
                f[i][j] = (f[i - 1][j] * j + f[i - 1][j - 1]) % mod
        return f[n][k]

Complexity

MeasureComplexity
TimeO(n \times k)
SpaceO(n \times k) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1692. Count Ways to Distribute Candies is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1692. Count Ways to Distribute Candies?
LeetCode 1692. Count Ways to Distribute Candies is rated Hard on LeetCode.
What is the time complexity of LeetCode 1692. Count Ways to Distribute Candies?
The Python solution on this page runs in O(n \times k).
What is the space complexity of LeetCode 1692. Count Ways to Distribute Candies?
The Python solution on this page uses O(n \times k) auxiliary space.
What topics does LeetCode 1692. Count Ways to Distribute Candies cover?
LeetCode 1692. Count Ways to Distribute Candies is tagged Dynamic Programming on LeetCode.
Is LeetCode 1692. Count Ways to Distribute Candies a premium problem?
Yes. LeetCode 1692. Count Ways to Distribute Candies is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview