Find the Closest Palindrome — LeetCode 564 Python Solution

HardMathString
Problem
#564
Reading time
4 min

The problem

Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.

Example

Input
n = "123"
Output
"121"

Python solution

Python
class Solution:
    def nearestPalindromic(self, n: str) -> str:
        x = int(n)
        l = len(n)
        res = {10 ** (l - 1) - 1, 10**l + 1}
        left = int(n[: (l + 1) >> 1])
        for i in range(left - 1, left + 2):
            j = i if l % 2 == 0 else i // 10
            while j:
                i = i * 10 + j % 10
                j //= 10
            res.add(i)
        res.discard(x)

        ans = -1
        for t in res:
            if (
                ans == -1
                or abs(t - x) < abs(ans - x)
                or (abs(t - x) == abs(ans - x) and t < ans)
            ):
                ans = t
        return str(ans)

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 564. Find the Closest Palindrome is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 564. Find the Closest Palindrome?
LeetCode 564. Find the Closest Palindrome is rated Hard on LeetCode.
What topics does LeetCode 564. Find the Closest Palindrome cover?
LeetCode 564. Find the Closest Palindrome is tagged Math and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview