<p>Given a string <code>n</code> representing an integer, return <em>the closest integer (not including itself), which is a palindrome</em>. If there is a tie, return <em><strong>the smaller one</strong></em>.</p>

<p>The closest is defined as the absolute difference minimized between two integers.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = &quot;123&quot;
<strong>Output:</strong> &quot;121&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = &quot;1&quot;
<strong>Output:</strong> &quot;0&quot;
<strong>Explanation:</strong> 0 and 2 are the closest palindromes but we return the smallest which is 0.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n.length &lt;= 18</code></li>
	<li><code>n</code> consists of only digits.</li>
	<li><code>n</code> does not have leading zeros.</li>
	<li><code>n</code> is representing an integer in the range <code>[1, 10<sup>18</sup> - 1]</code>.</li>
</ul>

class Solution:
    def nearestPalindromic(self, n: str) -> str:
        def mirror(part, is_even):
            left = part
            if not is_even:
                left = left // 10
            
            while left:
                dig = left % 10
                left //= 10
                part = part * 10 + dig
            
            return part

        possible = []

        size = len(n)
        is_even = size % 2 == 0
        half = (size // 2) - 1 if is_even else size // 2

        first_half = int(n[:half+1])
    
        res = mirror(first_half, is_even)
        
        possible.append(mirror(first_half, is_even))
        possible.append(mirror(first_half+1, is_even))
        possible.append(mirror(first_half-1, is_even))
        possible.append(10**(size-1) - 1)
        possible.append(10**(size) + 1)
        possible.sort()

        orig = int(n)
        best_diff = float("inf")
        ans = ""
        for p in possible:
            if p == orig:
                continue
            curr_diff = abs(orig - p)
            if curr_diff < best_diff:
                ans = p
                best_diff = curr_diff
            
        
        

        return str(ans)
16500