Given a string n representing an integer, return the closest integer (not including itself) that is a palindrome. If there is a tie, return the smaller one.
"Closest" is defined as minimizing the absolute difference between the two integers.
The usual approach mirrors the left half of n onto the right to form the nearest palindrome candidate, then also considers the mirrored half incremented and decremented by one, plus the two boundary palindromes made of all nines (e.g. 99, 999) and the form 10...01; the answer is whichever candidate (excluding n itself) has the smallest absolute difference, breaking ties toward the smaller value.
Interviewer-asked variant (per the Roblox interview report): solve it without converting the input to a string or array, handling the integer in place. The no-string variant performs the same digit-mirroring using arithmetic on the integer rather than string operations.
n = "123" return = "121"
n = "1" return = "0"
n = "10" return = "9"
1 <= n.length <= 18nconsists of digits only.ndoes not have leading zeros.nrepresents an integer in the range[1, 10^18 - 1].
- Candy Crush Grid Matching and GravityPHONE SCREEN · Seen Jun 2026
- Closest Binary Search Tree Value VariantPHONE SCREEN · Seen Jun 2026
- Design Search Autocomplete SystemPHONE SCREEN · Seen Jun 2026
- Grid Pathfinding with Obstacles (DFS)PHONE SCREEN · Seen Jun 2026
- Maximize Distance to Closest PersonPHONE SCREEN · Seen Jun 2026
- Maximum Number of Balls in a BoxPHONE SCREEN · Seen Jun 2026
- Meeting Rooms IIPHONE SCREEN · Seen Jun 2026
- Most Frequent Call Path From Function Trace LogsPHONE SCREEN · Seen Jun 2026
public String nearestPalindromic(String n) {
// write your code here
}