VOOZH about

URL: https://www.geeksforgeeks.org/dsa/closest-palindrome-number-whose-absolute-difference-min/

⇱ Closest Palindrome Number (absolute difference Is min) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Closest Palindrome Number (absolute difference Is min)

Last Updated : 21 Feb, 2025

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.

[Brute Force Approach] Iterate Backwards - O(n * d) Time and O(d) Space

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.


Output
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.

[Expected Approach] Manipulate First Half of the Number - O(d) Time and O(d) Space

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:

  • Convert the given number to a string for easy manipulation.
  • Extract the first half of the number as a substring.
  • Mirror this half to form a direct palindrome (Case 1).
  • Decrease the first half, mirror it to get a smaller palindrome (Case 2).
  • Increase the first half, mirror it to get a larger palindrome (Case 3).
  • Convert all three palindrome candidates back to integers.
  • Compare their absolute differences from the original number.
  • Return the closest palindrome; if ties exist, return the smallest one.

Output
484


Comment
Article Tags: