Problem · String

Find the Closest Palindrome

HardRobloxPHONE SCREEN
See Roblox hiring insights

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.

Examples
01 · Example 1
n = "123"
return = "121"
Both 121 and 131 differ from 123 by 2. On a tie, the smaller palindrome 121 wins.
02 · Example 2
n = "1"
return = "0"
0 and 2 are both 1 away from 1. Return the smaller one, 0.
03 · Example 3
n = "10"
return = "9"
The closest palindrome to 10 is 9 (difference 1); 11 is also difference 1, but 9 is smaller, so it wins the tie.
Constraints
  • 1 <= n.length <= 18
  • n consists of digits only.
  • n does not have leading zeros.
  • n represents an integer in the range [1, 10^18 - 1].
More Roblox problems
drafts saved locally
public String nearestPalindromic(String n) {
  // write your code here
}
n"123"
expected"121"
sign in to submit