Number of Distinct Roll Sequences - Problem

You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:

  • The greatest common divisor of any adjacent values in the sequence is equal to 1.
  • There is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2.

Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7.

Two sequences are considered distinct if at least one element is different.

Input & Output

Example 1 — Basic Case
$ Input: n = 4
Output: 184
💡 Note: For 4 dice rolls, there are 184 valid sequences satisfying both constraints: adjacent dice must have GCD=1 and same values must be separated by more than 2 positions.
Example 2 — Minimum Case
$ Input: n = 2
Output: 22
💡 Note: For 2 dice rolls, we need GCD(first, second) = 1. Valid pairs: (1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (2,1), (2,3), (2,5), (3,1), (3,2), (3,4), (3,5), (4,1), (4,3), (4,5), (5,1), (5,2), (5,3), (5,4), (5,6), (6,1), (6,5) = 22 total
Example 3 — Edge Case
$ Input: n = 1
Output: 6
💡 Note: With only 1 dice roll, any value 1-6 is valid since there are no adjacent values or gap constraints to check.

Constraints

  • 1 ≤ n ≤ 104

Visualization

Tap to expand
Distinct Roll Sequences - DP Approach INPUT 1 2 3 4 5 6 n = 4 GCD(adjacent) = 1 Gap of 2+ for equal values Roll dice 4 times mod 10^9 + 7 ALGORITHM STEPS 1 Define State dp[i][last][prev] roll i, last val, prev val 2 GCD Constraint Only allow adjacent pairs where GCD = 1 GCD=1 pairs: 1:[2,3,4,5,6] 2:[1,3,5] 3:[1,2,4,5] 4:[1,3,5] 5:[1,2,3,4,6] 6:[1,5] 3 Gap Constraint curr != last AND curr != prev (2-back) 4 Transition Sum all valid states for n=4 rolls FINAL RESULT Sample Valid Sequences: [1, 2, 1, 2] - OK [1, 3, 5, 2] - OK [5, 6, 1, 2] - OK Invalid Sequences: [2, 4, ...] GCD=2 [1, 2, 1, ...] gap<2 Total Distinct Sequences: 184 for n = 4 rolls Key Insight: Use 3D DP with state (position, last_value, second_last_value) to track last two dice values. For each new roll, check: 1) GCD with last value = 1, 2) Not equal to last or second-last. Time: O(n * 6 * 6 * 6) = O(n), Space: O(6 * 6) with optimization. TutorialsPoint - Number of Distinct Roll Sequences | Dynamic Programming Approach
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen