#3646
Next Special Palindrome Number
HardBacktrackingBit ManipulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Precompute special palindromes and use them to find the next one greater than n efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Generate all special palindromes up to a reasonable limit (e.g., 10^15).
- 2Step 2: Store them in a sorted list.
- 3Step 3: Use binary search to find the smallest special palindrome greater than n.
solution.py16 lines
1def generate_special_palindromes():
2 special_palindromes = []
3 for i in range(1, 10):
4 pal = int(str(i) * i)
5 special_palindromes.append(pal)
6 for i in range(1, 10):
7 for j in range(1, 10):
8 pal = int(str(i) + str(j) * j + str(i)[::-1])
9 special_palindromes.append(pal)
10 return sorted(special_palindromes)
11
12def next_special_palindrome(n):
13 special_palindromes = generate_special_palindromes()
14 for sp in special_palindromes:
15 if sp > n:
16 return spℹ
Complexity note: Generating special palindromes is linear in terms of the number of digits, and searching through them is efficient due to sorting.
- 1Special palindromes are limited in number, making precomputation feasible.
- 2Each digit k must appear exactly k times, which constrains the possible combinations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.