Find next and closest palindromes
UberSoftware Engineer · Online AssessmentLast updated
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.
Given a non-negative integer represented as a string n (no leading zeros unless n == "0"), return the smallest palindromic integer strictly greater than n. Return the answer as a string. Aim for O(n) time and O(
- extra space besides the output. Discuss how you handle edge cases such as all 9s, single-digit inputs, and length changes (e.g., "99" -> "101"). Follow-up A: Modify your solution to return the palindrome (not equal to n) with minimal absolute difference to n; if there is a tie, return the smaller palindrome. Explain which candidate palindromes you generate and how you compare magnitudes without using big-integer libraries. Follow-up B: If the input is a decimal number with a fixed number of fractional digits (e.g., "123.450"), define a palindromic decimal as one where the '.' mirrors itself and the digits mirror across it. Return the smallest palindromic decimal strictly greater than the input under this definition. Describe how you propagate carries across the decimal point and how you preserve the fixed fractional length.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.