Number of Dice Rolls With Target Sum explained
To count the ways d dice with f faces can add up to a target, build the answer one die at a time: ways[s] is the number of rolls so far that total s, and adding a die sets new[s] to the sum of ways[s - 1] through ways[s - f]. That table takes O(d * target * f) time; keeping a running window sum of the last f entries cuts it to O(d * target). Return 0 at once if the target is below d or above d * f, and keep every count modulo 1,000,000,007.
By Evin JohnPublished 7 min read
The problem in plain words
You roll d dice. Each die shows a whole number from 1 to f, and the dice are told apart, so a 2 on the first die and a 5 on the second is a different roll from a 5 then a 2. Count how many of the f^d possible rolls add up exactly to a given target. Because the count grows very quickly, the answer is reported as its remainder after division by 1,000,000,007.
| Dice | Faces | Target | Ways |
|---|---|---|---|
| 3 | 6 | 10 | 27 |
| 5 | 6 | 17 | 780 |
| 4 | 4 | 16 | 1 (every die shows 4) |
| 2 | 6 | 13 | 0 (above 2 * 6) |
| 25 | 12 | 200 | 244,060,502 after the remainder |
What the interviewer listens for
The problem is a clean check of dynamic-programming habits. Interviewers want a precise state (number of dice so far and the running total), a transition stated in one sentence, sensible base cases, and attention to the remainder. Strong candidates then notice that the inner loop sums a contiguous block of the previous row and replace it with a sliding window. Mentioning the quick range check, and why order matters here when it does not in coin change, rounds out a good answer.
Follow-ups that come up
- What if the dice were not distinguishable? Then you would count multisets of values, which is a partition-style count with faces as the outer loop, as in Coin Change II.
- Return the probability instead. Divide the exact count by f^d. Use exact integers or fractions; floating point loses precision for many dice.
- Faces with arbitrary values. Replace the window with a loop over the face values; the window trick depends on faces being consecutive.
- Answer many targets at once. The final row already holds the count for every total, so one pass answers them all.
Brute force and the plain table
Listing every roll with a product loop is the honest first step, and it doubles as the test reference. It is f^d work, so it only survives a handful of dice. The table replaces the list with counts. Start with one way to make total 0 using zero dice. For each die, the number of ways to reach total s is the number of ways the earlier dice reached s - 1, s - 2 and so on down to s - f, because the new die covers the difference. After d rounds, read the entry for the target.
@@number-of-dice-rolls-with-target-sum/slow.py@@The faster version: a sliding window
Look at what the inner loop adds: ways[s - 1] + ways[s - 2] + ... + ways[s - f], a block of f consecutive entries from the previous row. When s grows by one, the block gains ways[s - 1] at the top and loses ways[s - f - 1] at the bottom. Keep that block sum in a variable and update it with one addition and one subtraction per step. The faces loop disappears and each die costs O(target). A prefix-sum array does the same job and is just as acceptable to describe.
@@number-of-dice-rolls-with-target-sum/fast.py@@Python's % always returns a non-negative result, so subtracting and then taking the remainder is safe. JavaScript's % keeps the sign of the left side, so a window that dips below zero after a subtraction would stay negative. The JavaScript version adds MOD before subtracting, which keeps the value non-negative and still below 3 * MOD, far inside the range where numbers are exact.
@@number-of-dice-rolls-with-target-sum/fast.js@@A small trace
Three six-sided dice, target 10. After one die, totals 1 to 6 each have one way. After two dice, the counts for totals 2 to 12 rise and fall: 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1. For the third die, total 10 is the sum of the two-dice counts for totals 4 through 9, which is 3 + 4 + 5 + 6 + 5 + 4 = 27. The window version gets the same 27 by sliding along that row rather than adding six entries for every total.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| List every roll | O(f^d * d) | O(d) |
| Memoized recursion on (dice left, total left) | O(d * t * f) | O(d * t) plus the call stack |
| Row-by-row table | O(d * t * f) | O(t) |
| Row-by-row table with a window sum | O(d * t) | O(t) |
Two easy savings are worth a sentence. Totals above the target never matter, so each row stops at t. And if t is outside the range from d to d * f, the answer is 0 before any work.
Edge cases
- Target below the number of dice, or above dice times faces: return 0.
- Target exactly d or exactly d * f: one way, all ones or all maximums.
- One face per die: one way when the target equals the number of dice, otherwise none.
- One die: one way for any target from 1 to f.
- Large inputs whose true count is far beyond 64 bits; the remainder is required, not optional.
Mistakes to avoid
- Starting the table at ways[0] = 0, which makes every later count 0.
- Letting the window include ways[s - f - 1] or miss ways[s - 1]: write out the first two totals to check the bounds.
- A negative window in JavaScript or Java after a subtraction.
- Putting faces in the outer loop and totals in the inner one in a single shared array, which counts unordered combinations of faces and ignores the dice count.
- Taking the remainder only at the end, after the numbers have already overflowed in a fixed-width language.
How to explain it out loud
Fictional example
- Candidate
- My state is how many dice I've placed and the total so far. With zero dice there's one way to have total zero.
- Candidate
- Adding a die, the ways to reach s are the ways the previous dice reached s minus 1 down to s minus f. That's d times target times f.
- Interviewer
- Can you do better?
- Candidate
- The inner sum is a window of f consecutive cells, so I'll keep a running sum and slide it: add the new cell, drop the old one, take the remainder. That makes each die linear in the target.
Related problems
Profitable Schemes is another counting table that reports its answer modulo a large prime. Knight Dialer also builds counts one step at a time, but over keypad positions instead of totals. Ones and Zeroes is the take-or-skip cousin, and Stone Game fills its table by range length instead of by step. Climbing Stairs is this exact problem with two faces and no limit on the number of dice, and Coin Change II shows what changes when order stops mattering.
Using Natively in practice sessions
This one is short enough to run several times in a week, each time trying to reach the window version faster. Natively on a Mac or Windows PC can pick up the problem from a screenshot, check your transition when the base case goes wrong, and ask the indistinguishable-dice follow-up. Reading the transcript of the mock afterwards shows whether you stated the state before you started typing.
Questions people ask
How do you count dice rolls that sum to a target?
Build counts one die at a time. ways[s] is the number of rolls so far that total s; adding a die sets new[s] to ways[s - 1] + ... + ways[s - f]. After d dice, read the entry for the target.
How do you make the dice roll DP faster?
The inner sum covers f consecutive entries of the previous row, so keep a running window sum: add ways[s - 1], drop ways[s - f - 1]. Each die then costs O(target) instead of O(target * f).
What is the time complexity of Number of Dice Rolls With Target Sum?
O(d * target * f) for the plain table and O(d * target) with the window sum, both with O(target) memory.
Why is the answer taken modulo 1,000,000,007?
The number of rolls grows exponentially with the number of dice and soon exceeds any fixed-size integer, so the problem asks for the remainder. Take it after every addition.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
