#2318

Number of Distinct Roll Sequences

Hard
Dynamic ProgrammingMemoizationDynamic ProgrammingMemoization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use dynamic programming to build valid sequences incrementally while keeping track of the last two rolls. This way, we can efficiently calculate the number of valid sequences without generating all possibilities.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a DP array where dp[i][j] represents the number of valid sequences of length i ending with the value j.
  2. 2Step 2: Initialize base cases for sequences of length 1.
  3. 3Step 3: For each length from 2 to n, calculate the number of valid sequences by considering the last roll and ensuring the conditions are met.
  4. 4Step 4: Sum up all valid sequences of length n and return the result modulo 10^9 + 7.
solution.py23 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def count_sequences(n):
5    dp = [[0] * 7 for _ in range(n + 1)]
6    for j in range(1, 7):
7        dp[1][j] = 1
8
9    for i in range(2, n + 1):
10        for j in range(1, 7):
11            for k in range(1, 7):
12                if gcd(j, k) == 1:
13                    dp[i][j] = (dp[i][j] + dp[i - 1][k]) % MOD
14            if i > 2:
15                for k in range(1, 7):
16                    if j != k:
17                        dp[i][j] = (dp[i][j] + dp[i - 2][k]) % MOD
18
19    result = sum(dp[n]) % MOD
20    return result
21
22# Example usage
23print(count_sequences(4))  # Output: 184

Complexity note: The time complexity is O(n) because we iterate through the sequence lengths and the possible last rolls, while the space complexity is O(n) due to the DP table storing results for each roll length.

  • 1Understanding GCD properties helps in filtering valid sequences quickly.
  • 2Dynamic programming can significantly reduce the complexity by avoiding redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.