Sponsored
Sponsored
This approach involves mirroring the first half of the number to form the second half which can create a potential palindrome. After forming the basic mirrored palindrome, consider the numbers formed by adjusting the half upwards and downwards. This will cover all possible close numbers. Finally, choose the closest and smallest palindrome by comparing all options.
Time Complexity: O(n) where n is the length of the string, as it involves mirroring which is a linear operation.
Space Complexity: O(n) for storing temporary palindrome strings.
1function mirrorPalindrome(s) {
2 let n = s.length;
3 let result = s.split('');
4 for (let i = 0; i < Math.floor(n / 2); i++) {
5 result[n - 1 - i] = s[i];
6 }
7 return parseInt(result.join(''));
8}
9
10function closestPalindrome(n) {
11 let original = parseInt(n);
12 let best = Number.MAX_SAFE_INTEGER;
13
14 // Generate basic, lower and higher mirroring
15 let lower = n.split('');
16 let higher = n.split('');
17
18 let mirrorValue = mirrorPalindrome(n);
19
20 // Compare different mirroring options
21 if (mirrorValue !== original) best = mirrorValue;
22
23 lower[Math.floor((n.length-1)/2)] = String.fromCharCode(lower[Math.floor((n.length-1)/2)].charCodeAt(0) - 1);
24 let lowMirror = mirrorPalindrome(lower.join(''));
25 if (Math.abs(lowMirror - original) < Math.abs(best - original) || (Math.abs(lowMirror - original) === Math.abs(best - original) && lowMirror < best)) {
26 best = lowMirror;
27 }
28
29 higher[Math.floor((n.length-1)/2)] = String.fromCharCode(higher[Math.floor((n.length-1)/2)].charCodeAt(0) + 1);
30 let highMirror = mirrorPalindrome(higher.join(''));
31 if (Math.abs(highMirror - original) < Math.abs(best - original) || (Math.abs(highMirror - original) === Math.abs(best - original) && highMirror < best)) {
32 best = highMirror;
33 }
34
35 return best.toString();
36}
The JavaScript solution uses array handling to generate mirrored numbers for candidate selection. By carefully adjusting the character array, various possibilities for palindromes closest to the original number are analyzed and returned.