<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:
    prevPalindrome, nextPalindrome = self._getPalindromes(n)
    return (str(prevPalindrome)
            if abs(prevPalindrome - int(n)) <= abs(nextPalindrome - int(n))
            else str(nextPalindrome))

  def _getPalindromes(self, s: str) -> tuple[str, str]:
    """Returns the two closest palindromes to the given number."""
    num = int(s)
    sz = len(s)
    palindromes = []
    half = s[0:(sz + 1) // 2]
    reversedHalf = half[:sz // 2][::-1]
    candidate = int(half + reversedHalf)

    if candidate < num:
      palindromes.append(candidate)
    else:
      prevHalf = str(int(half) - 1)
      reversedPrevHalf = prevHalf[:sz // 2][::-1]
      if sz % 2 == 0 and int(prevHalf) == 0:
        palindromes.append(9)
      elif sz % 2 == 0 and prevHalf == '9':
        palindromes.append(int(prevHalf + '9' + reversedPrevHalf))
      else:
        palindromes.append(int(prevHalf + reversedPrevHalf))

    if candidate > num:
      palindromes.append(candidate)
    else:
      nextHalf = str(int(half) + 1)
      reversedNextHalf = nextHalf[:sz // 2][::-1]
      palindromes.append(int(nextHalf + reversedNextHalf))

    return palindromes
16600