#564
Find the Closest Palindrome
HardMathStringString ManipulationGreedy Algorithms
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)
The optimal approach focuses on generating only a few specific palindrome candidates based on the structure of the input number, which drastically reduces the number of checks needed. By only considering the first half of the number, we can create potential palindromes efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Identify the length of the input number and its prefix.
- 2Step 2: Generate palindromes based on the prefix, adjusting it slightly to account for potential closest palindromes.
- 3Step 3: Compare the generated palindromes to find the closest one, ensuring to exclude the original number.
solution.py21 lines
1# Full working Python code
2
3def closest_palindrome(n):
4 num = int(n)
5 candidates = set()
6 candidates.add(num - 1)
7 candidates.add(num + 1)
8 length = len(n)
9 prefix = int(n[:(length + 1) // 2])
10 for i in [-1, 0, 1]:
11 candidate = str(prefix + i)
12 if length % 2 == 0:
13 palindrome = candidate + candidate[::-1]
14 else:
15 palindrome = candidate + candidate[-2::-1]
16 candidates.add(int(palindrome))
17 candidates.discard(num)
18 return str(min(candidates, key=lambda x: (abs(x - num), x)))
19
20# Example usage
21print(closest_palindrome('123'))ℹ
Complexity note: The optimal solution runs in O(n) time because we only generate a few specific candidates based on the input's prefix, rather than checking all possible palindromes. The space complexity is O(n) due to the storage of candidates.
- 1Generating palindromes based on the prefix of the number significantly reduces the number of candidates to check.
- 2When comparing candidates, ensure to handle ties by choosing the smaller number.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.