Find the nearest palindromic integer to a numeric string, excluding the number itself
Company: Yelp
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Other
Overview: Given a positive integer written as a digit string of up to 18 characters, find the nearest palindromic integer other than the number itself, with ties going to the smaller value. It tests building a small candidate set from the first half of the number and handling the cases where the digit count changes.
Constraints
- 1 <= len(n) <= 18
- n consists only of digits and has no leading zeros.
- n represents an integer from 1 to 10^18 - 1.
Examples
Input: ('1',)
Expected Output: '0'
Explanation: Source example: 1 itself is excluded, 0 and 2 tie at distance 1, and the smaller 0 wins.
Input: ('9',)
Expected Output: '8'
Explanation: Largest single digit: 8 is 1 away, 10 is not a palindrome, and 11 is 2 away.
Hints
- Values reach 10^18 + 1, past the range where a double-precision float is exact, so keep every comparison exact (64-bit integers, or BigInt in JavaScript).
- The examples 100 and 1 show that the closest palindrome can have fewer digits than n. Consider when it could have more digits.
- n itself never counts, so a palindromic n still needs the nearest other palindrome on each side, and a tie goes to the smaller value.