Solving Leetcode Interviews in Seconds with AI: Number of Distinct Roll Sequences
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2318" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. 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 <= 104
Explanation
Here's a breakdown of the approach and the Python code:
- Dynamic Programming: Use dynamic programming to store the number of valid sequences ending with a particular dice value. The state
dp[i][j]stores the number of valid sequences of lengthiending with the valuej. - GCD and Gap Constraints: Iterate through possible previous rolls to check the GCD condition and the gap condition.
Modulo Arithmetic: Apply the modulo operator at each step to prevent integer overflow.
Runtime Complexity: O(n), Storage Complexity: O(n)
Code
import math
def solve():
n = int(input())
MOD = 10**9 + 7
dp = [[0] * 7 for _ in range(n + 1)]
# Initialize base case: sequences of length 1
for i in range(1, 7):
dp[1][i] = 1
for i in range(2, n + 1):
for j in range(1, 7):
for k in range(1, 7):
if math.gcd(j, k) == 1:
if i > 2:
can_add = True
for l in range(i - 2, 0, -1):
if dp[l][j] > 0:
can_add = False
break
if can_add:
dp[i][j] = (dp[i][j] + dp[i - 1][k]) % MOD
else:
dp[i][j] = (dp[i][j] + dp[i - 1][k]) % MOD
total_sequences = 0
for i in range(1, 7):
total_sequences = (total_sequences + dp[n][i]) % MOD
print(total_sequences)
solve()