Smallest Palindromic Number Strictly Greater Than n, Up to 18 Digits
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Overview: Given a positive integer of up to 18 digits as a string, return the smallest palindromic number strictly greater than it, or the input itself when no such palindrome stays within 18 digits. Tests digit-level reasoning and edge cases such as palindromic inputs, carries and changes in digit count.
Constraints
- 1 <= len(n) <= 18
- n contains only the digits 0 to 9 and has no leading zero, so its value is between 1 and 10^18 - 1
- Values can exceed 2^31 - 1 and 2^53, so they are passed and returned as decimal strings; every eligible value fits in a signed 64-bit integer
- The gap between n and the answer can exceed 10^9, so testing numbers one at a time is too slow
- The result has at most 18 digits; if no palindrome p satisfies n < p <= 999999999999999999, return n unchanged
Examples
Input: ('1',)
Expected Output: '2'
Explanation: Smallest valid input; every single digit is a palindrome, so the next one is 2.
Input: ('9',)
Expected Output: '11'
Explanation: No single digit exceeds 9, so the answer grows to the smallest two-digit palindrome.
Hints
- Decide the answer's digit count first: can it have the same number of digits as n, or must it be longer?
- Two decimal strings of equal length without leading zeros compare in the same order as the numbers they represent, so the 18-digit values never need to be converted.
- Only a few inputs have no eligible answer: those where every larger palindrome would need more than 18 digits.