Number of Dice Rolls With Target Sum - Problem

You have n dice, and each dice has k faces numbered from 1 to k.

Given three integers n, k, and target, return the number of possible ways (out of the k^n total ways) to roll the dice, so the sum of the face-up numbers equals target.

Since the answer may be too large, return it modulo 10^9 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 1, k = 6, target = 3
Output: 1
💡 Note: With 1 die having 6 faces, only one way to get sum 3: roll a 3
Example 2 — Multiple Ways
$ Input: n = 2, k = 6, target = 7
Output: 6
💡 Note: With 2 dice, 6 ways to get sum 7: (1,6), (2,5), (3,4), (4,3), (5,2), (6,1)
Example 3 — Impossible Target
$ Input: n = 30, k = 30, target = 500
Output: 222616187
💡 Note: Large case with many combinations, result modulo 10^9 + 7

Constraints

  • 1 ≤ n, k ≤ 30
  • 1 ≤ target ≤ 1000

Visualization

Tap to expand
Number of Dice Rolls With Target Sum INPUT 1 die with 6 faces n = 1 dice k = 6 faces target=3 sum goal Possible faces: 1,2,3,4,5,6 Need sum = 3 1 2 3 4 5 6 ALGORITHM STEPS 1 Define DP State dp[i][j] = ways to get sum j using i dice 2 Base Case dp[0][0] = 1 (0 dice, sum 0 = 1 way) 3 Transition For each face f (1 to k): dp[i][j] += dp[i-1][j-f] 4 Return Answer Return dp[n][target] mod 10^9 + 7 DP Table (n=1, target=3) sum 0 1 2 3 i=1 0 1 1 1 FINAL RESULT Roll showing 3 Output: 1 OK - Verified! Only face 3 = target 3 Key Insight: Dynamic Programming builds solutions incrementally. dp[i][j] counts ways to achieve sum j using exactly i dice. For each new die, we try all k faces and sum up the ways from the previous state. Time: O(n * target * k). With n=1 die, the only way to get sum=3 is rolling face 3, hence answer is 1. TutorialsPoint - Number of Dice Rolls With Target Sum | DP Approach
Asked in
Amazon 15 Google 12 Microsoft 8
125.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