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
Dice Roll Combinations: n=2, k=6, target=7Die 1Die 2Sum167257347Valid combination 1Valid combination 2Valid combination 3... and 3 more: (4,3), (5,2), (6,1)Total Ways: 6DP counts all validcombinations efficiently
Understanding the Visualization
1
Input
n=2 dice, k=6 faces each, target=7
2
Process
Find all valid combinations that sum to target
3
Output
Count = 6 different ways
Key Takeaway
🎯 Key Insight: Use dynamic programming to build up solutions for smaller subproblems and combine them efficiently
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