897. Prime Palindrome
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the smallest prime palindrome number that is greater than or equal to a given integer n. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. A palindrome is a number that reads the same forwards and backwards.
Solution
Prime Palindrome in Python
class Solution:
def primePalindrome(self, n: int) -> int:
"""
Finds the smallest prime palindrome greater than or equal to n.
"""
def is_prime(num: int) -> bool:
"""Helper function to check for primality."""
if num < 2 or num % 2 == 0:
return num == 2
# Check for divisibility by odd numbers up to sqrt(num)
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
return False
return True
# All even-length palindromes are divisible by 11, except 11 itself.
# If n is between 8 and 11, the next prime palindrome must be 11.
if 8 <= n <= 11:
return 11
# We can generate odd-length palindromes from a root number.
# e.g., root 123 generates palindrome 12321.
# Max answer is 2*10^8 (9 digits), root will have 5 digits.
# So we can search roots up to 10^5.
for i in range(1, 100000):
s = str(i)
# Construct odd-length palindrome string
# s[:-1] reverses all but the last character
# e.g., s="123", s[:-1]="12", s[:-1][::-1]="21"
# p = "123" + "21" = "12321"
p_str = s + s[:-1][::-1]
p = int(p_str)
# If we generate a palindrome greater than the max possible answer, we can stop.
if p > 2 * 10**8:
break
if p >= n and is_prime(p):
return p
return -1 # Should not be reached based on problem constraints
Prime Palindrome in Java
class Solution {
// Helper function to check if a number is prime.
private boolean isPrime(int num) {
if (num < 2 || num % 2 == 0) {
return num == 2;
}
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public int primePalindrome(int n) {
// All even-length palindromes (except 11) are divisible by 11.
// If n is between 8 and 11, the answer is 11.
if (n >= 8 && n <= 11) {
return 11;
}
// We generate odd-length palindromes from roots 1, 2, 3, ...
// An odd-length palindrome is defined by its first half (root).
// e.g., root 123 -> palindrome 12321.
// The largest answer is 2*10^8 (9 digits), so its root has at most 5 digits.
// We can limit the search for roots up to 100000.
for (int i = 1; i < 100000; i++) {
// Construct the odd-length palindrome from the root `i`.
String s = Integer.toString(i);
String reversed_s = new StringBuilder(s).reverse().toString();
// For root "123", palindrome is "123" + "21" = "12321"
String palindromeStr = s + reversed_s.substring(1);
int p = Integer.parseInt(palindromeStr);
// Check if it's the smallest prime palindrome >= n.
if (p >= n && isPrime(p)) {
return p;
}
}
// This return is for completeness, based on problem constraints it won't be reached.
return -1;
}
}
Prime Palindrome in C++
class Solution {
public:
// Helper function to check if a number is prime.
bool isPrime(int num) {
if (num < 2 || num % 2 == 0) {
return num == 2;
}
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
int primePalindrome(int n) {
// Base cases and handling the only even-length prime palindrome (11).
// If n is between 8 and 11, the next prime palindrome is 11.
if (n >= 8 && n <= 11) {
return 11;
}
// We generate odd-length palindromes from roots 1, 2, 3, ...
// An odd-length palindrome is determined by its first half (root).
// e.g., root 123 -> palindrome 12321.
// The largest answer is 2*10^8 (9 digits), its root is a 5-digit number.
// So we can cap the root search at 100000.
for (int i = 1; i < 100000; ++i) {
// Construct the odd-length palindrome from root `i`.
string s = to_string(i);
string t = s;
reverse(t.begin(), t.end());
string palindrome_str = s + t.substr(1);
// Using long to avoid overflow, although problem constraints suggest int is fine.
long p = stol(palindrome_str);
// If the palindrome is out of bounds, we can stop.
if (p > 200000000) {
break;
}
// Check if it's the smallest prime palindrome >= n.
if (p >= n && isPrime(p)) {
return p;
}
}
// This part should not be reached based on problem constraints.
return -1;
}
};
Prime Palindrome in TypeScript
/**
* Checks if a number is prime.
* @param num The number to check.
* @returns True if the number is prime, false otherwise.
*/
function isPrime(num: number): boolean {
if (num < 2 || num % 2 === 0) {
return num === 2;
}
for (let i = 3; i * i <= num; i += 2) {
if (num % i === 0) {
return false;
}
}
return true;
}
/**
* @param {number} n
* @return {number}
*/
function primePalindrome(n: number): number {
// All even-length palindromes (except 11) are divisible by 11.
// If n is between 8 and 11, the answer is 11.
if (n >= 8 && n <= 11) {
return 11;
}
// We generate odd-length palindromes from roots 1, 2, 3, ...
// An odd-length palindrome is defined by its first half (root).
// e.g., root 123 -> palindrome 12321.
// The largest answer is 2*10^8 (9 digits), so its root has at most 5 digits.
// We can limit the search for roots up to 100000.
for (let i = 1; i < 100000; i++) {
const s = i.toString();
const reversedS = s.split('').reverse().join('');
// For root "123", palindrome is "123" + "21" = "12321"
const palindromeStr = s + reversedS.substring(1);
const p = parseInt(palindromeStr, 10);
// If the palindrome is out of bounds, we can stop.
if (p > 200000000) {
break;
}
// Check if it's the smallest prime palindrome >= n.
if (p >= n && isPrime(p)) {
return p;
}
}
// This return is for completeness, based on problem constraints it won't be reached.
return -1;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.