Dice Roll Simulation — LeetCode 1223 Python Solution
- Problem
- #1223
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
@cache
def dfs(i, j, x):
if i >= n:
return 1
ans = 0
for k in range(1, 7):
if k != j:
ans += dfs(i + 1, k, 1)
elif x < rollMax[j - 1]:
ans += dfs(i + 1, j, x + 1)
return ans % (10**9 + 7)
return dfs(0, 0, 0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times k^2 \times M) |
| Space | O(n \times k \times M) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1223. Dice Roll Simulation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1223. Dice Roll Simulation?
- LeetCode 1223. Dice Roll Simulation is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1223. Dice Roll Simulation?
- The Python solution on this page runs in O(n \times k^2 \times M).
- What is the space complexity of LeetCode 1223. Dice Roll Simulation?
- The Python solution on this page uses O(n \times k \times M) auxiliary space.
- What topics does LeetCode 1223. Dice Roll Simulation cover?
- LeetCode 1223. Dice Roll Simulation is tagged Array and Dynamic Programming on LeetCode.