Leetcode #1223: Dice Roll Simulation
In this guide, we solve Leetcode #1223 Dice Roll Simulation in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
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:
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.