#1223
Dice Roll Simulation
HardArrayDynamic ProgrammingDynamic ProgrammingState Transition
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * 6 * 6) |
| Space | O(1) | O(n * 6) |
💡
Intuition
Time O(n * 6 * 6)Space O(n * 6)
Using dynamic programming, we can efficiently count valid sequences by maintaining a state that tracks the last rolled number and how many times it has been rolled consecutively. This avoids generating all sequences explicitly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[i][j] represents the number of valid sequences of length i ending with the number j.
- 2Step 2: Iterate through each length from 1 to n, and for each possible last roll, calculate valid sequences based on previous rolls.
- 3Step 3: Use the rollMax constraints to limit how many times a number can be repeated consecutively.
solution.py17 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def dieSimulator(n, rollMax):
5 dp = [[0] * 6 for _ in range(n + 1)]
6 for j in range(6):
7 dp[1][j] = 1
8 for i in range(2, n + 1):
9 for j in range(6):
10 for k in range(6):
11 if j != k:
12 dp[i][j] = (dp[i][j] + sum(dp[i - 1])) % MOD
13 else:
14 for m in range(1, rollMax[j] + 1):
15 if i - m >= 0:
16 dp[i][j] = (dp[i][j] + dp[i - m][j]) % MOD
17 return sum(dp[n]) % MODℹ
Complexity note: The time complexity is O(n * 6 * 6) because we iterate through each roll length (n), and for each last roll (6 options), we check against all other rolls (6 options).
- 1Dynamic programming is essential for optimizing problems with overlapping subproblems.
- 2Understanding constraints helps in designing the state transitions effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.