Number of Dice Rolls With Target Sum - Problem

Imagine you're at a board game night with n dice, and each die has k faces numbered from 1 to k. Your challenge is to find how many different ways you can roll these dice so that the sum of all face-up numbers equals a specific target.

For example, with 2 dice (each having 6 faces) and a target sum of 7, you could roll (1,6), (2,5), (3,4), (4,3), (5,2), or (6,1) - that's 6 different ways!

The Goal: Count all possible combinations of dice rolls that sum to the target value.

Input: Three integers n (number of dice), k (faces per die), and target (desired sum)

Output: Number of ways to achieve the target sum, modulo 109 + 7 (since the result can be very large)

Note: With n dice having k faces each, there are kn total possible outcomes, but we only want those that sum to our target!

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 1, k = 6, target = 3
โ€บ Output: 1
๐Ÿ’ก Note: With 1 six-sided die, there's only one way to get sum 3: roll a 3.
example_2.py โ€” Multiple Ways
$ Input: n = 2, k = 6, target = 7
โ€บ Output: 6
๐Ÿ’ก Note: With 2 six-sided dice, we can get sum 7 in 6 ways: (1,6), (2,5), (3,4), (4,3), (5,2), (6,1).
example_3.py โ€” Impossible Target
$ Input: n = 30, k = 30, target = 500
โ€บ Output: 222616187
๐Ÿ’ก Note: Large case where the answer needs to be returned modulo 10^9 + 7.

Constraints

  • 1 โ‰ค n โ‰ค 30
  • 1 โ‰ค k โ‰ค 30
  • 1 โ‰ค target โ‰ค 1000
  • Return result modulo 109 + 7

Visualization

Tap to expand
Cookie Distribution ProblemC1C2C33 Children (dice), each gets 1-6 cookies (faces)Target: 7 cookies total2 cookies3 cookies2 cookiesOne valid distribution: (2,3,2) = 7 totalDP Subproblemdp(children_left,cookies_remaining)= ways to distributeEach distribution method corresponds to a dice roll combination
Understanding the Visualization
1
Setup the party
We have n children (dice) and need to distribute target cookies total
2
Give cookies to first child
First child can get 1 to k cookies - try each possibility
3
Recursive distribution
For each choice, distribute remaining cookies to remaining children
4
Count valid distributions
Sum up all ways where exactly target cookies are distributed
Key Takeaway
๐ŸŽฏ Key Insight: Break the problem into subproblems - to distribute cookies to n children, try each possible amount for the first child, then recursively solve for the remaining children with updated constraints.
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
89.0K Views
Medium Frequency
~25 min Avg. Time
2.8K 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