Prime Palindrome - Problem

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 * 10⁸].

Input & Output

Example 1 — Small Number
$ Input: n = 9
Output: 11
💡 Note: Starting from 9: 9 is palindrome but not prime (divisible by 3), 10 is not palindrome, 11 is both palindrome and prime (only divisible by 1 and 11)
Example 2 — Already Prime Palindrome
$ Input: n = 2
Output: 2
💡 Note: 2 itself is both prime and palindrome, so return 2
Example 3 — Larger Input
$ Input: n = 13
Output: 101
💡 Note: 13 is prime but not palindrome. Next palindromes are 22, 33, 44, etc. but they're not prime. 101 is the first prime palindrome ≥ 13

Constraints

  • 1 ≤ n ≤ 2 × 108
  • The answer always exists and is in the range [2, 2 × 108]

Visualization

Tap to expand
Prime Palindrome Problem: n = 9Input: n = 9Find prime palindrome ≥ 9Palindrome?reads same both waysPrime?only divisors: 1, itselfAnswer: 1111 is palindrome AND primeCheck candidates starting from 9:91011palindrome, not primenot palindromepalindrome AND prime ✓Result: 11 is the smallest prime palindrome ≥ 9
Understanding the Visualization
1
Input
Given n = 9, find prime palindrome ≥ 9
2
Check Conditions
Number must be palindrome AND prime
3
Output
Return 11 (palindrome: 11, prime: only divisors are 1, 11)
Key Takeaway
🎯 Key Insight: Even-length palindromes (except 11) are divisible by 11, so focus on odd-length palindromes for efficiency
Asked in
Google 15 Facebook 10 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen