bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 564. Find the Closest Palindrome

564. Find the Closest Palindrome

Leetcode Solutions

Finding the Closest Palindrome Using Mathematical Replication and Adjustment

  1. Convert the input string n to an integer and store it as num.
  2. If num is less than 10 or is 11, return num - 1 as a string, since the closest palindrome would be the previous number.
  3. Generate the first candidate a by mirroring the first half of n onto the second half.
  4. Generate the second candidate b by decrementing the middle digit of n (if it's not '0') and then mirroring the first half.
  5. Generate the third candidate c by incrementing the middle digit of n (if it's not '9') and then mirroring the first half.
  6. Convert all candidates to integers and calculate their absolute differences from num.
  7. Among the candidates, find the one with the smallest absolute difference from num. In case of a tie, choose the smaller palindrome.
  8. Return the closest palindrome as a string.
UML Thumbnail

Brute Force Search for Closest Palindrome

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...