Problem Description
You are given an integer n representing the number of times you roll a fair 6-sided dice. You need to count the number of distinct sequences of rolls such that:
- The greatest common divisor (gcd) of every pair of adjacent dice outcomes is 1.
- If two rolls have the same value, there must be at least a gap of 2 rolls between them (i.e., if the value of the i-th roll equals the j-th roll, then |i - j| > 2). Return the total number of valid sequences modulo 10^9 + 7.
Key Insights
- The adjacent gcd condition implies that only pairs (a, b) where gcd(a, b) = 1 are allowed. Precomputing the valid transitions between dice values (1-6) is useful.
- The gap restriction prevents immediate repetition with an intervening roll, effectively requiring tracking of at least the last two outcomes.
- A dynamic programming (DP) strategy is ideal where the state includes information about the last one or two dice outcomes.
- Since n can be as large as 10^4, it is important to design the DP to run in O(n) time (or with a small constant factor) and use space-optimization techniques.
Space and Time Complexity
Time Complexity: O(n) (with a small constant factor since we are iterating over a fixed set of dice faces and precomputed valid transitions) Space Complexity: O(1) when optimizing DP with a sliding window (only storing states for the last two rolls)
Solution
We use dynamic programming with a state that captures the last two outcomes. Let dp[i][prev1][prev2] represent the number of valid sequences of length i ending with "prev1" as the last roll and "prev2" as the roll before that (using a placeholder for sequences shorter than 2). When adding a new roll "newFace":
- Ensure gcd(prev1, newFace) equals 1.
- If prev2 equals newFace (and prev2 is not just a placeholder), the move is invalid because it violates the gap condition. A precomputed transition map for valid dice pairs (based on gcd) simplifies the update step. Finally, we sum over all valid end states after constructing sequences of length n and return the result modulo 10^9 + 7.
Code Solutions
Below are solutions in Python, JavaScript, C++, and Java.