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 modulo109 + 7.
Two sequences are considered distinct if at least one element is different.
Example 1:
Input: n = 4
Output: 184
Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.
Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).
(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).
(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.
There are a total of 184 distinct sequences possible, so we return 184.
Example 2:
Input: n = 2
Output: 22
Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).
Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.
There are a total of 22 distinct sequences possible, so we return 22.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
4
Example 2
2
Related Problems
Dice Roll Simulation (dice-roll-simulation)
Paint House III (paint-house-iii)
Step 02
Core Insight
What unlocks the optimal approach
Can you think of a DP solution?
Consider a state that remembers the last 1 or 2 rolls.
Do you need to consider the last 3 rolls?
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2318: Number of Distinct Roll Sequences
class Solution {
public int distinctSequences(int n) {
if (n == 1) {
return 6;
}
int mod = (int) 1e9 + 7;
int[][][] dp = new int[n + 1][6][6];
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 6; ++j) {
if (gcd(i + 1, j + 1) == 1 && i != j) {
dp[2][i][j] = 1;
}
}
}
for (int k = 3; k <= n; ++k) {
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 6; ++j) {
if (gcd(i + 1, j + 1) == 1 && i != j) {
for (int h = 0; h < 6; ++h) {
if (gcd(h + 1, i + 1) == 1 && h != i && h != j) {
dp[k][i][j] = (dp[k][i][j] + dp[k - 1][h][i]) % mod;
}
}
}
}
}
}
int ans = 0;
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 6; ++j) {
ans = (ans + dp[n][i][j]) % mod;
}
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
// Accepted solution for LeetCode #2318: Number of Distinct Roll Sequences
func distinctSequences(n int) int {
if n == 1 {
return 6
}
dp := make([][][]int, n+1)
for k := range dp {
dp[k] = make([][]int, 6)
for i := range dp[k] {
dp[k][i] = make([]int, 6)
}
}
for i := 0; i < 6; i++ {
for j := 0; j < 6; j++ {
if gcd(i+1, j+1) == 1 && i != j {
dp[2][i][j] = 1
}
}
}
mod := int(1e9) + 7
for k := 3; k <= n; k++ {
for i := 0; i < 6; i++ {
for j := 0; j < 6; j++ {
if gcd(i+1, j+1) == 1 && i != j {
for h := 0; h < 6; h++ {
if gcd(h+1, i+1) == 1 && h != i && h != j {
dp[k][i][j] = (dp[k][i][j] + dp[k-1][h][i]) % mod
}
}
}
}
}
}
ans := 0
for i := 0; i < 6; i++ {
for j := 0; j < 6; j++ {
ans = (ans + dp[n][i][j]) % mod
}
}
return ans
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
# Accepted solution for LeetCode #2318: Number of Distinct Roll Sequences
class Solution:
def distinctSequences(self, n: int) -> int:
if n == 1:
return 6
mod = 10**9 + 7
dp = [[[0] * 6 for _ in range(6)] for _ in range(n + 1)]
for i in range(6):
for j in range(6):
if gcd(i + 1, j + 1) == 1 and i != j:
dp[2][i][j] = 1
for k in range(3, n + 1):
for i in range(6):
for j in range(6):
if gcd(i + 1, j + 1) == 1 and i != j:
for h in range(6):
if gcd(h + 1, i + 1) == 1 and h != i and h != j:
dp[k][i][j] += dp[k - 1][h][i]
ans = 0
for i in range(6):
for j in range(6):
ans += dp[-1][i][j]
return ans % mod
// Accepted solution for LeetCode #2318: Number of Distinct Roll Sequences
/**
* [2318] Number of Distinct Roll Sequences
*
* 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:
* <ol>
* 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 i^th roll is equal to the value of the j^th roll, then abs(i - j) > 2.
* </ol>
* Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 10^9 + 7.
* Two sequences are considered distinct if at least one element is different.
*
* Example 1:
*
* Input: n = 4
* Output: 184
* Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.
* Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).
* (1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).
* (1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.
* There are a total of 184 distinct sequences possible, so we return 184.
* Example 2:
*
* Input: n = 2
* Output: 22
* Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).
* Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.
* There are a total of 22 distinct sequences possible, so we return 22.
*
*
* Constraints:
*
* 1 <= n <= 10^4
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/number-of-distinct-roll-sequences/
// discuss: https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn distinct_sequences(n: i32) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2318_example_1() {
let n = 4;
let result = 184;
assert_eq!(Solution::distinct_sequences(n), result);
}
#[test]
#[ignore]
fn test_2318_example_2() {
let n = 2;
let result = 22;
assert_eq!(Solution::distinct_sequences(n), result);
}
}
// Accepted solution for LeetCode #2318: Number of Distinct Roll Sequences
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2318: Number of Distinct Roll Sequences
// class Solution {
// public int distinctSequences(int n) {
// if (n == 1) {
// return 6;
// }
// int mod = (int) 1e9 + 7;
// int[][][] dp = new int[n + 1][6][6];
// for (int i = 0; i < 6; ++i) {
// for (int j = 0; j < 6; ++j) {
// if (gcd(i + 1, j + 1) == 1 && i != j) {
// dp[2][i][j] = 1;
// }
// }
// }
// for (int k = 3; k <= n; ++k) {
// for (int i = 0; i < 6; ++i) {
// for (int j = 0; j < 6; ++j) {
// if (gcd(i + 1, j + 1) == 1 && i != j) {
// for (int h = 0; h < 6; ++h) {
// if (gcd(h + 1, i + 1) == 1 && h != i && h != j) {
// dp[k][i][j] = (dp[k][i][j] + dp[k - 1][h][i]) % mod;
// }
// }
// }
// }
// }
// }
// int ans = 0;
// for (int i = 0; i < 6; ++i) {
// for (int j = 0; j < 6; ++j) {
// ans = (ans + dp[n][i][j]) % mod;
// }
// }
// return ans;
// }
//
// private int gcd(int a, int b) {
// return b == 0 ? a : gcd(b, a % b);
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.