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 Palindrome INPUT String n representing integer 1 2 3 [0] [1] [2] Input Value: n = "123" 100 123 150 Find nearest palindrome to 123 on number line ALGORITHM STEPS 1 Get Middle Part Extract prefix: "12" 2 Generate Candidates Mirror: 121, 111, 131 121 111 131 3 Calculate Differences |123-121|=2, |123-111|=12 121: |123-121| = 2 111: |123-111| = 12 131: |123-131| = 8 4 Select Minimum Min diff = 2 --> "121" FINAL RESULT Closest Palindrome Found 121 Palindrome Verified: 1 2 1 mirrors Output: "121" OK - Difference: 2 Key Insight: Generate palindrome candidates by mirroring the first half. Consider edge cases: numbers with all 9s (999-->1001), all 0s after 1 (100-->99), and increment/decrement of middle digit. Compare absolute differences to find closest. TutorialsPoint - Find the Closest Palindrome | Mathematical Palindrome Generation
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