Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the ways to roll n dice with k faces each so that the faces sum to target (mod 10⁹ + 7).

Problem: Count the ways to roll n dice with k faces each so that the faces sum to target (mod 10⁹ + 7).
def dice(n, k, target, MOD=10**9 + 7):
    dp = [1] + [0] * target
    for _ in range(n):
        new = [0] * (target + 1)
        for s in range(target + 1):
            if dp[s]:
                for f in range(1, k + 1):
                    if s + f <= target: new[s + f] = (new[s + f] + dp[s]) % MOD
        dp = new
    return dp[target]
print(dice(2, 6, 7), dice(3, 4, 6), dice(2, 3, 7))
What is printed?
  1. A. 6 10 0
  2. B. 6 7 0
  3. C. 3 10 0
  4. D. 6 10 1

Correct answer: A. 6 10 0

Layer by layer: dp after i dice counts ordered outcomes for each sum. Two d6 → 7: (1,6) … (6,1) = 6 (ordered, so 3 would be the unordered count). Three d4 → 6: compositions of 6 into 3 parts of 1–4 = C(5, 2) − 0 = 10. Two d3 cannot exceed 6 → 0. O(n · target · k).

More Coding Interview Problems questions

Exams that ask this topic