Magicsheet logo

Prime Palindrome

Medium
12.5%
Updated 8/1/2025

Asked by 3 Companies

Prime Palindrome

What is this problem about?

The Prime Palindrome problem asks for the smallest prime palindrome greater than or equal to n. A palindrome is a number that reads the same forwards and backwards; a prime palindrome must be both. This coding problem requires generating palindromes and checking primality. The math and number theory interview pattern is demonstrated.

Why is this asked in interviews?

Meta, Amazon, and Google ask this to test number generation with multiple constraints. The key mathematical insight: all even-digit palindromes (except 11) are divisible by 11 and thus not prime. This prunes the search space dramatically.

Algorithmic pattern used

Skip even-length palindromes + primality check. For each candidate starting from n: check if it's a palindrome and prime. Skip all even-digit palindromes (they're multiples of 11 except 11 itself). Generate odd-digit palindromes directly: for k digits where k is odd, enumerate the first (k+1)//2 digits and mirror them. Check primality with Miller-Rabin or trial division.

Example explanation

n=6. Check: 6 not prime. 7 is prime AND palindrome → 7. n=8. 8,9 not prime+palindrome. 10,11: 11 is prime palindrome → 11. n=13. 13 is prime but not palindrome. Next palindromes: 101 (prime ✓) → 101.

Common mistakes candidates make

  • Not skipping even-digit palindromes (slows down search significantly).
  • Slow primality check for large numbers.
  • Not handling n=1 correctly (smallest prime palindrome ≥ 1 is 2).
  • Off-by-one in palindrome generation.

Interview preparation tip

Prime Palindrome is an intersection problem: generate candidates satisfying both properties. The even-digit palindrome insight (divisible by 11) is a key optimization. For efficient palindrome generation: iterate over the "half" of a palindrome and mirror it. Practice generating palindromes of length k directly — it's faster than checking each number individually for palindromicity.

Similar Questions