Find the Closest Palindrome - 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.

Input & Output

Example 1 — Basic Case
$ Input: n = "123"
Output: "121"
💡 Note: The closest palindromes are 121 (distance 2) and 131 (distance 8). Since 121 is closer, we return "121".
Example 2 — Single Digit
$ Input: n = "1"
Output: "0"
💡 Note: For single digit input, the closest palindrome is simply the digit minus 1 (except for 0 which returns 1).
Example 3 — Edge Case 99
$ Input: n = "99"
Output: "101"
💡 Note: The candidates are 9 (distance 90) and 101 (distance 2). 101 is much closer, so return "101".

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, 1018 - 1]

Visualization

Tap to expand
Find the Closest Palindrome123Input NumberGenerate Palindrome Candidates:991011211311001Distances: 24, 22, 2, 8, 878Closest: 121 (distance = 2)
Understanding the Visualization
1
Input
Given number as string (e.g., "123")
2
Generate
Create palindrome candidates mathematically
3
Compare
Return closest palindrome (prefer smaller if tie)
Key Takeaway
🎯 Key Insight: Only 5 palindrome candidates need to be checked for any number
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen