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 Dice Roll Sequences (n=4)Find sequences satisfying GCD and gap constraints3412Valid Sequence ExamplePos 1Pos 2Pos 3Pos 4Constraints Check✓ GCD(3,4) = 1✓ GCD(4,1) = 1✓ GCD(1,2) = 1✓ No repeats within gap of 2All constraints satisfied!2436Invalid Sequence ExampleConstraint Violation✗ GCD(4,2) = 2 ≠ 1Adjacent GCD constraint failedAnswer: 184 valid sequences for n=4
Understanding the Visualization
1
Input
n = 4 dice rolls to make
2
Constraints
GCD(adjacent) = 1, gap > 2 for same values
3
Count
Find all valid sequences modulo 10^9+7
Key Takeaway
🎯 Key Insight: Use DP to track (position, last_roll, second_last_roll) states efficiently
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