Find the Closest Palindrome

String, Math

Hard

Given an integer n, find the closest integer (not including itself), which is a palindrome.

The 'closest' is defined as absolute difference minimized between two integers.

Example 1:

Input:
 "123"

Output:
 "121"

Note:

  1. The input n is a positive integer represented by string, whose length will not exceed 18.

  2. If there is a tie, return the smaller one as answer.

Solution

Based on: @fun4LeetCode's answer:

https://leetcode.com/problems/find-the-closest-palindrome/discuss/102389/Java-solution-with-detailed-proof

8 ms, faster than 98.75%

3 steps:

I -- The given number itself is a palindrome

II -- The given number is a not palindrome

III -- Construct the whole palindrome from its left part

Construct a palindrome based on left half, then find the nearest palindrome larger or smaller than curP: nextP, prevP. Then compare the diff between num, cur, prev, next.

LeetCode official

Using Math:

  • Time complexity : O(l). Scanning, insertion, deletion,, mirroring takes O(l), wherellis the length of the string.

  • Space complexity : O(l). Temporary variables are used to store the strings.

Reference

https://leetcode.com/problems/find-the-closest-palindrome/solution/

Last updated

Was this helpful?