Skip to main content
LeetCode 564, Hard. Topics: Math, String. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 27 parametrized pytest cases, and a playground notebook:

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. The closest is defined as the absolute difference minimized between two integers.

Examples

Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.

Constraints

  • 1 <= n.length <= 18
  • n consists of only digits.
  • n does not have leading zeros.
  • n is representing an integer in the range [1, 10^18 - 1].

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026