Python 1223.py
class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
# roll 0...5 instead of 1...6 (zero-indexing) to simplify code
modulo = 1_000_000_007
# seed values: roll each number once
have = []
for i in range(6):
have.append([ 1 ] + [ 0 ] * (rollMax[i] - 1))
for _ in range(n - 1):
each = [ sum(have[j]) % modulo for j in range(6) ]
all = sum(each)
for i in range(6):
# roll a different number (sum of all sequences not ending in current number)
other = all - each[i]
# prepend "other", discard the impossible value at index rollMax[i]
have[i].insert(0, other)
have[i].pop()
return sum(sum(h) for h in have) % modulo
Difficulty
and has an acceptance rate of about 51% (70k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the number of possible sequences of dice rolls of length n where each face may appear consecutively at most a given limit (rollMax). The algorithm builds the count incrementally, maintaining for each die face a sliding window that records how many sequences end with that face and a specific run length. By updating these windows for each additional roll, the final answer is obtained as the sum of all windows modulo 1 000 000 007.
Key Steps
The class defines a single method dieSimulator. The first operation establishes a modulus constant to keep intermediate results within integer bounds.
modulo = 1_000_000_007
Next, the algorithm creates the initial state for each of the six faces. For each face i, a list of length rollMax[i] is built. The first element is set to 1, representing the single-roll sequence that ends with that face, while the remaining positions are initialized to 0 because longer runs are impossible at the start.
have = []
for i in range(6):
have.append([1] + [0] * (rollMax[i] - 1))
The main loop runs n-1 times, because the first roll has already been accounted for in the seed values. Inside the loop, the total number of sequences that currently end with each face is computed by summing the corresponding window. This produces a list each where each[i] holds the total count for face i. The overall total across all faces is stored in all.
each = [sum(have[j]) % modulo for j in range(6)]
all = sum(each)
For each face i, the algorithm determines how many new sequences can be formed by appending a roll of a different face. This quantity, named other, is the global total minus the sequences that already end with face i.
other = all - each[i]
The sliding window for face i is then updated. The value other is inserted at the front of the list, representing the new sequences that now end with a single occurrence of face i. Simultaneously, the last element of the list is removed, discarding counts that would exceed the allowed consecutive limit for that face.
have[i].insert(0, other)
have[i].pop()
After processing all faces for the current roll, the loop proceeds to the next iteration. When the loop finishes, the final answer is obtained by summing every entry in every window and applying the modulus.
return sum(sum(h) for h in have) % modulo
Edge Cases Handled
The initialization step creates a window whose length matches each entry of rollMax. When rollMax[i] equals 1, the list for that face contains a single element. The subsequent insert and pop operations still function correctly: inserting a new count at the front pushes the existing element out, effectively enforcing the rule that the face cannot appear consecutively more than once.
If n is 1, the outer loop (for _ in range(n - 1)) executes zero times. The method then directly returns the sum of the seed values, which correctly counts the six possible single-roll outcomes.
When rollMax[i] is larger than n, the window size exceeds the number of rolls that could possibly fill it. The algorithm still maintains the full window, but entries beyond the current roll count remain zero, ensuring they do not contribute to the final sum.
The subtraction other = all - each[i] may produce a negative intermediate value if the modulus is not applied immediately. However, the subsequent insertion of other into the window and the final modulo operation guarantee that the final result stays within the required range.
Performance Optimizations
The solution avoids constructing full DP tables of size n × 6 × max(rollMax). Instead, it keeps only six sliding windows, each of length at most the corresponding rollMax[i]. This reduces memory usage dramatically, especially when n is large.
By computing each[i] as the sum of the current window for face i, the algorithm reuses previously calculated values rather than recomputing sums from scratch for every possible run length. The modulo operation is applied early to each each[i], preventing integer overflow during the accumulation of all.
The use of list insert(0, ...) and pop() implements a constant-time shift of the window contents because Python lists are optimized for appending and popping at the end; inserting at the front is O(k) where k is the window size, but the window size is bounded by rollMax[i], which is at most 15 in typical problem constraints. This bounded size keeps the per-iteration cost low.
Finally, the final aggregation sum(sum(h) for h in have) traverses each window only once after all rolls have been processed, avoiding repeated summations inside the main loop. This separation of concerns ensures that the inner loop focuses solely on updating windows, while the final sum is performed in a single pass.
ELI5 - Simplified Explanation
Imagine a game where you have six dice, and each one has a special rule about how many times in a row it is allowed to show the same number. To figure out how many ways the dice can land after a certain number of tosses, the computer keeps a little list for each die.
At the start, the computer remembers that each number has happened once so far. When it is time to roll again, the computer looks at all the previous rolls and thinks about which numbers are safe to pick next. If a die has reached its limit for one-in-a-row or two-in-a-row, the computer excludes that choice so the rules stay followed.
The computer then updates its lists by taking the new safe choices and sliding them to the front, while removing the oldest, impossible choices from the back. It repeats this process for every toss until it reaches the total number of rolls asked for. By adding up all the ways that are still left in the lists, it finds the total number of valid sequences.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | Python | |||||||
| leetcode.ca | C++ | Java | Go | Python | ||||
| MemoryLimitExceeded | C++ | Python | ||||||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lzl124631x | C++ | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | Python | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| MemoryLimitExceeded | Python, C++ | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lzl124631x | C++ | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 2028: Find Missing Observations
- problem 2318: Number of Distinct Roll Sequences
Solved On The Same Day
- problem 1144: Decrease Elements To Make Array Zigzag
- problem 1156: Swap For Longest Repeated Character Substring
- problem 1224: Maximum Equal Frequency
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality