![]() |
VOOZH | about |
Given an integer num, the task is to find the closest Palindrome number whose absolute difference with the given number is minimal. If 2 Palindrome numbers have the same absolute difference as the given number, take the smaller one.
Examples:
Input: num = 9
Output: 9
Explanation: 9 itself is a palindrome number.Input: num = 489
Output: 484
Explanation: Closest palindrome numbers from 489 are 484 and 494. Since both have the same absolute difference, we return the smaller one, which is 484.Input: num = 1234
Output: 1221
Explanation: Closest palindrome numbers from 1234 are 1221 and 1331. Since 1221 is closer than 1331, we return 1221.
Table of Content
The idea is to find the nearest palindrome by checking both smaller and larger numbers. We decrement from the given number to find the largest smaller palindrome and increment to find the smallest larger palindrome. The closest one is returned based on the absolute difference.
484
Time Complexity: O(n*d), as we first iterate backward from num and then forward from num until we find a palindromic number, which can approximately run for O(n) times and for checking if its a palindrome it takes d time, where d is the number of digits in the number.
Auxiliary Space: O(d), as at every iteration we create a string to store the number.
The idea is to construct three candidate palindromes by manipulating the first half of the number. First, we mirror the first half to get a direct palindrome. Then, we decrease the first half and mirror it to get a smaller palindrome. Finally, we increase the first half and mirror it to get a larger palindrome. The closest palindrome is determined by comparing the absolute differences from the original number.
Steps to implement the above idea:
484