Solving Leetcode Interviews in Seconds with AI: Prime Palindrome
Introduction
In this blog post, we will explore how to solve the LeetCode problem "866" 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
Given an integer n, return the smallest prime palindrome greater than or equal to n. An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number. For example, 2, 3, 5, 7, 11, and 13 are all primes. An integer is a palindrome if it reads the same from left to right as it does from right to left. For example, 101 and 12321 are palindromes. The test cases are generated so that the answer always exists and is in the range [2, 2 * 108]. Example 1: Input: n = 6 Output: 7 Example 2: Input: n = 8 Output: 11 Example 3: Input: n = 13 Output: 101 Constraints: 1 <= n <= 108
Explanation
Here's a breakdown of the approach and the Python code:
Approach:
- Generate palindromes starting from the smallest possible palindrome greater than or equal to the input
n. - Check each generated palindrome for primality.
- Return the first palindrome that is both prime and greater than or equal to
n. We optimize by generating only odd length palindromes for larger numbers, and handling the special case of single digit numbers.
- Generate palindromes starting from the smallest possible palindrome greater than or equal to the input
Complexity:
- Runtime Complexity: O(sqrt(N) * log(N)), where N is the result. The
log(N)factor arises because of the palindrome generation, and thesqrt(N)is due to primality testing. - Storage Complexity: O(1)
- Runtime Complexity: O(sqrt(N) * log(N)), where N is the result. The
Code
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def generate_palindrome(length):
start = 10 ** ((length - 1) // 2)
end = 10 ** ((length + 1) // 2)
for i in range(start, end):
s = str(i)
palindrome = s + s[:(length // 2)][::-1]
yield int(palindrome)
def prime_palindrome(n):
if n <= 2:
return 2
if n <= 3:
return 3
if n <= 5:
return 5
if n <= 7:
return 7
if n <= 11:
return 11
length = len(str(n))
if length % 2 == 0:
length += 1
while True:
for palindrome in generate_palindrome(length):
if palindrome >= n and is_prime(palindrome):
return palindrome
length += 2