Find the Closest Palindrome - Problem

You're given a string n representing a positive integer, and your task is to find the closest palindromic number to it (excluding the number itself).

A palindrome reads the same forwards and backwards, like 121, 1331, or 9. The "closest" palindrome is the one with the minimum absolute difference from the original number.

Special case: If there are two palindromes with the same distance (a tie), return the smaller one.

Examples:

  • n = "123" → return "121" (difference of 2)
  • n = "1" → return "0" (closest smaller palindrome)
  • n = "99" → return "101" (next palindrome is closer than 88)

Input & Output

example_1.py — Basic Case
$ Input: n = "123"
Output: "121"
💡 Note: The closest palindromes are 121 (difference of 2) and 131 (difference of 8). Since 121 is closer, we return "121".
example_2.py — Single Digit
$ Input: n = "1"
Output: "0"
💡 Note: For single digit numbers, the closest smaller palindrome is n-1. So for "1", the answer is "0".
example_3.py — Edge Case
$ Input: n = "99"
Output: "101"
💡 Note: The candidates are: 88 (diff=11) and 101 (diff=2). Since 101 is much closer, we return "101".

Visualization

Tap to expand
123499912211331111110001Closest!Mathematical candidate generation finds the closest palindrome efficiently
Understanding the Visualization
1
Identify the Pattern
Palindromes are symmetric - we only need to focus on the left half
2
Generate Smart Candidates
Create 5 strategic candidates based on mathematical properties
3
Handle Edge Cases
Special patterns like 999→1001 and 100→99 need special handling
4
Choose Optimal
Select the candidate with minimum difference (prefer smaller if tied)
Key Takeaway
🎯 Key Insight: Instead of checking every number, generate only 5 mathematically optimal candidates based on palindrome structure properties.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Where n is the length of the number string. We generate at most 5 candidates.

n
2n
Linear Growth
Space Complexity
O(1)

Only using constant extra space for candidate generation

n
2n
Linear Space

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]
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 23
28.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