#906
Super Palindromes
HardMathStringEnumerationEnumerationTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the fact that we can generate palindromic numbers directly and only check their squares. This reduces the number of checks significantly and avoids iterating through all numbers in the range.
⚙️
Algorithm
4 steps- 1Step 1: Generate palindromic numbers up to the square root of right.
- 2Step 2: For each palindromic number, compute its square.
- 3Step 3: Check if the square is a palindrome and falls within the range [left, right].
- 4Step 4: Count valid super-palindromes.
solution.py18 lines
1def is_palindrome(x): return str(x) == str(x)[::-1]
2
3def super_palindromes(left, right):
4 left, right = int(left), int(right)
5 count = 0
6 for i in range(1, 100000):
7 s = str(i)
8 pal = int(s + s[::-1]) # Even length palindromes
9 pal_sq = pal * pal
10 if pal_sq > right: break
11 if pal_sq >= left and is_palindrome(pal_sq):
12 count += 1
13 pal = int(s + s[-2::-1]) # Odd length palindromes
14 pal_sq = pal * pal
15 if pal_sq > right: break
16 if pal_sq >= left and is_palindrome(pal_sq):
17 count += 1
18 return countℹ
Complexity note: This complexity is efficient because we only generate palindromic numbers and check their squares, significantly reducing the number of iterations.
- 1Super-palindromes must be both palindromic and squares of palindromic numbers.
- 2Generating palindromic numbers directly is more efficient than checking every number.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.