Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Dice rolls with a target sum

Medium · Target 20 minutes · Dynamic programming · Type asked atAmazonTwo Sigma

You roll n dice, each with faces 1 to k. Return the number of ordered outcomes (one face per die) whose sum is target, modulo 10⁹ + 7.

Examples

InputOutputWhy
n = 1, k = 6, target = 31Roll a 3.
n = 2, k = 6, target = 761+6, 2+5, 3+4, 4+3, 5+2, 6+1.
n = 30, k = 30, target = 500222616187Modulo 10⁹ + 7.

Constraints

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

Hints

Hint 1

The state needs the number of dice rolled, not just the sum: ways[d][s].

Hint 2

ways[d][s] = Σ over faces f of ways[d − 1][s − f].

Hint 3

Keep one row per die; reduce modulo 10⁹ + 7 after every addition.

Where people lose marks

  • Dropping the dice count from the state, which allows any number of dice.
  • Forgetting the modulus until the end, which overflows.
  • Counting unordered outcomes.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.