Find next and closest palindromes
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: This question evaluates string-based numeric manipulation and palindrome construction, including edge-case handling (all 9s, single-digit inputs, length changes), candidate generation and magnitude comparison of large numbers as strings, and carry propagation for fixed-length decimal palindromes.
Next Greater Palindrome
Constraints
- n is a non-negative integer string with no leading zeros except "0".
- The returned palindrome must be strictly greater than n.
Examples
Input: ('12345',)
Expected Output: '12421'
Explanation: Mirroring is too small, so the prefix is incremented.
Input: ('12932',)
Expected Output: '13031'
Explanation: Incrementing the prefix gives the next larger palindrome.
Input: ('99',)
Expected Output: '101'
Explanation: All nines grow the length.
Input: ('8',)
Expected Output: '9'
Explanation: Single non-nine digits increment directly.
Hints
- First mirror the left half to the right.
- If mirroring is not enough, increment the middle prefix and mirror again.
Closest Palindrome
Constraints
- n is a non-negative integer string with no leading zeros except "0".
- If two palindromes are equally close, return the smaller numeric value.
Examples
Input: ('123',)
Expected Output: '121'
Explanation: The closest palindrome is below the input.
Input: ('1',)
Expected Output: '0'
Explanation: The closest palindrome not equal to 1 is 0.
Input: ('99',)
Expected Output: '101'
Explanation: The nearest palindrome is 101.
Input: ('1000',)
Expected Output: '999'
Explanation: 999 and 1001 tie, so the smaller one wins.
Hints
- Generate palindromes from prefix - 1, prefix, and prefix + 1.
- Also include boundary candidates such as 99..9 and 100..001.