#866

Prime Palindrome

Medium
MathNumber TheoryMathNumber Theory
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking every number, we can generate palindromic numbers directly and then check if they are prime. This is more efficient because it reduces the number of candidates we need to check.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate palindromic numbers starting from n.
  2. 2Step 2: For each palindromic number, check if it is prime.
  3. 3Step 3: Return the first palindromic number that is also prime.
solution.py25 lines
1# Full working Python code
2
3def is_prime(num):
4    if num < 2:
5        return False
6    for i in range(2, int(num**0.5) + 1):
7        if num % i == 0:
8            return False
9    return True
10
11def generate_palindrome(num):
12    s = str(num)
13    return int(s + s[::-1][1:])  # Generate even-length palindrome
14
15def prime_palindrome(n):
16    if n <= 2:
17        return 2
18    for length in range(1, 9):  # Generate palindromes of increasing lengths
19        for half in range(10**(length-1), 10**length):
20            pal = generate_palindrome(half)
21            if pal >= n and is_prime(pal):
22                return pal
23            pal = generate_palindrome(half) + 1  # Odd-length palindrome
24            if pal >= n and is_prime(pal):
25                return pal

Complexity note: The time complexity is O(n) because we generate palindromic numbers directly, significantly reducing the number of candidates we need to check for primality.

  • 1Generating palindromic numbers directly reduces the search space.
  • 2Checking for primality can be optimized by only checking up to the square root.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.