Leetcode #2318: Number of Distinct Roll Sequences
In this guide, we solve Leetcode #2318 Number of Distinct Roll Sequences in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an integer n. You roll a fair 6-sided dice n times.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Memoization, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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.
Python Solution
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
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.