Nearest Palindromic Number
Updated
Problem statement
The decimal string number represents a positive integer without leading zeroes. Find the closest nonnegative integer whose digits read the same forward and backward. It must be different from the input number. Return it as a decimal string.
Distance is the absolute numeric difference. If two palindromes are equally close, return the smaller one. The returned representation has no leading zeroes, except that zero is written "0".
Function
nearestPalindrome(number: String) → StringExamples
Example 1
number = "121"return = "111"The input itself is excluded. Both 111 and 131 are ten away, so the smaller 111 wins.
Example 2
number = "123"return = "121"Keep the first two digits and copy the first digit onto the end. That gives the palindrome in the output, only two below the input. Every other palindrome is farther away, so that is the answer.
Example 3
number = "1"return = "0"Zero and two are equally close, so zero wins.
Constraints
1 <= number.length <= 18.- The input contains decimal digits only and represents a positive integer.
More Apple Onsite Interview questions
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Dec 2026
- Topological OrderingPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- FIFO Mutex Operation TraceONSITE INTERVIEW · Seen Oct 2026
- Implement Hit CounterPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Parse Nested HTML into a TreeONSITE INTERVIEW · Seen Oct 2026
- Thread-Safe Concurrent Linked ListONSITE INTERVIEW · Seen Sep 2026
- Palindrome Match PercentageONSITE INTERVIEW · Seen Sep 2026
- Binary Tree Nodes at Distance KONSITE INTERVIEW · Seen Aug 2026
- BST to Sorted Circular Doubly Linked ListONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- Transform L/R Pieces on a Circular BoardGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Integer to English Words: Up to 20 DigitsPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Roman to IntegerKotak Mahindra Bank · PHONE SCREEN · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Iterate Canonical IPv6 AddressesOpenAI · ONSITE INTERVIEWOpenAI interview questions
- Convert Hexadecimal to Dotted IPv4Microsoft · ONSITE INTERVIEWMicrosoft interview questions
- Bit at an Index After Repeated Binary ExpansionAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Text Embedding and Vector SearchNike, Inc. · PHONE SCREEN · ONSITE INTERVIEWNike, Inc. interview questions
- Fraction to Recurring DecimalGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Most Cost-Effective MachineCapital One · ONSITE INTERVIEWCapital One interview questions