> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Find the Closest Palindrome Python Solution

> Tested Python solution for LeetCode 564 with 27 pytest cases. Generate a practice environment with lcpy.

LeetCode 564, [Hard](/catalog/hard). Topics: [Math](/catalog/topics/math), [String](/catalog/topics/string). [View on LeetCode](https://leetcode.com/problems/find-the-closest-palindrome/description/).

Generate this problem as a practice environment: tested reference solution, 27 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 564   # by problem number
lcpy gen -s find_the_closest_palindrome   # by problem name
```

## 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

```
Input: n = "123"
Output: "121"
```

```
Input: n = "1"
Output: "0"
```

**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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_the_closest_palindrome/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_the_closest_palindrome/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(len(n))
    # Space: O(len(n))
    def nearest_palindromic(self, n: str) -> str:
        num = int(n)
        length = len(n)
        candidates: set[int] = {10 ** (length - 1) - 1, 10**length + 1}
        prefix = int(n[: (length + 1) // 2])
        for p in (prefix - 1, prefix, prefix + 1):
            left = str(p)
            mirrored = left if length % 2 == 0 else left[:-1]
            candidates.add(int(left + mirrored[::-1]))
        candidates.discard(num)
        best: int = candidates.pop()
        for cand in candidates:
            if (abs(cand - num), cand) < (abs(best - num), best):
                best = cand
        return str(best)
```

## Complexity

| Time | Space |
| - | - |
| O(len(n)) | O(len(n)) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.