Find the Closest Palindrome

HardMathmath

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a positive integer as a decimal string n. Return, as a string, the palindrome integer closest to it, **not counting n itself**. "Closest" means the smallest absolute difference. If two palindromes are equally close, return the smaller one. Distances are measured between integer values, and 0 counts as a palindrome. n can have up to 18 digits, so stepping outward one integer at a time is too slow in general. Think about which few candidates can possibly win.

Examples

Input: n = "123"
Output: "121"
121 is 2 away; the next closest palindrome, 131, is 8 away.
Input: n = "1"
Output: "0"
0 and 2 are both 1 away; the smaller one wins.
Input: n = "99"
Output: "101"
99 itself does not count. 101 is 2 away while 88 is 11 away.

Constraints

  • 1 <= n.length <= 18
  • `n` consists only of digits
  • `n` has no leading zeros
  • `n` represents an integer in the range [1, 10^18 - 1]

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More math problems