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?- A. 6 10 0
- B. 6 7 0
- C. 3 10 0
- 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
- Problem: Picking a value v earns v points but deletes every v − 1 and v + 1 from the array; repeat until empty. Maximise points (reduces…
- Problem: Make two strings equal by deleting characters; the cost is the sum of ASCII codes of deleted characters. Minimise it (a weighted…
- Problem: Find the longest bitonic subsequence (strictly increasing then strictly decreasing; either part may be empty) using LIS from the…
- Problem: Numbers whose only prime factors are 2, 3 and 5 (1 included) are generated in order with three pointers. python def ugly(n): u =…
- Problem: A chess knight hops on a phone keypad (1-9 in a 3 × 3 grid, 0 below 8). Count the distinct numbers of length n it can dial (start…
- Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two…