Dice Roll Simulation Problem
Description
LeetCode Problem 1223.
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 10^9 + 7.
Two sequences are considered different if at least one element differs from each other.
Example 1:
Input: n = 2, rollMax = [1,1,2,2,2,3]
Output: 34
Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.
Example 2:
Input: n = 2, rollMax = [1,1,1,1,1,1]
Output: 30
Example 3:
Input: n = 3, rollMax = [1,1,1,2,2,3]
Output: 181
Constraints:
1 <= n <= 5000rollMax.length == 61 <= rollMax[i] <= 15
Solution
Approach: Dynamic Programming on the Current Run
Whether the next roll is allowed depends only on the last face and how many times in a row it has come up. So build the sequences roll by roll and keep run[j][x]: the number of sequences so far that end with exactly x rolls of face j in a row. After the first roll, run[j][1] = 1 for every face.
To go from one roll to the next, look at what the new roll does:
- A different face than the last one starts a new run of length 1. So the new
run[j][1]is the number of sequences that do not end inj: the total of all counts minus the counts of facej. - The same face extends the run, which is only allowed while it stays within the limit: the new
run[j][x] = run[j][x-1]for2 <= x <= rollMax[j]. A run already at its limit cannot be extended and simply disappears.
After n rolls the answer is the sum of all counts. Everything is taken modulo 109 + 7. One trap: the subtraction total - (counts of j) can go negative after taking remainders, so add the modulus back before the final % (Python's % already returns a non-negative result).
Complexity: O(n · 6 · M) time, where M = 15 is the largest run length, and O(6 · M) extra space, since only the previous roll is kept.
class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
mod = 10**9 + 7
# run[j][x] = sequences so far that end in exactly x rolls of face j in a row
run = [[0] * 16 for _ in range(6)]
for j in range(6):
run[j][1] = 1
for _ in range(n - 1):
total = sum(map(sum, run)) % mod
nxt = [[0] * 16 for _ in range(6)]
for j in range(6):
# Start a new run of j after any sequence that does not end in j.
nxt[j][1] = (total - sum(run[j])) % mod
# Or extend a run of j, as long as it stays within rollMax[j].
for x in range(2, rollMax[j] + 1):
nxt[j][x] = run[j][x - 1]
run = nxt
return sum(map(sum, run)) % mod