Skip to content
Problem 564 · LeetCode 564(opens in a new tab)

Find the Closest Palindrome

HardMath

You are given a positive whole number as a string n. Find the palindrome (a number that reads the same forwards and backwards) that is nearest to it, and return it as a string. n itself does not count, even when it is a palindrome.

Nearest means the smallest absolute difference. If one palindrome below and one above are equally near, return the smaller.

Example 1

Input:  n = "4127"
Output: "4114"
Why:    4114 is 13 below; the next one up, 4224, is 97 above
2 more examples and the constraints

Example 2

Input:  n = "10"
Output: "9"
Why:    9 and 11 are both 1 away; take the smaller

Example 3

Input:  n = "999"
Output: "1001"
Why:    999 itself is excluded; 1001 is 2 away, 989 is 10

Constraints

  • 1 ≤ length of n ≤ 18
  • n holds only digits and has no leading zeros
  • n is between 1 and 10¹⁸ − 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Five candidatesO(L)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for an 18-digit nVerdict
Binary search on the mirrorO(L · log N)
Fast; about 120 mirrors
Five candidatesO(L)
Best; five mirrors and a compare

L = number of digits in n (at most 18), N = the value of n.

Edge cases to test

  • n is a palindrome. "11" must not return itself; the answer is 9.
  • All nines. "999" jumps up a length to 1001.
  • Power of ten. "1000" drops a length to 999; "10" ties 9 and 11 and returns 9.
  • Single digit. "1" returns "0", the tie with 2 going to the smaller.
  • Near the top. For 18 nines the answer is 10¹⁸ + 1, which still fits in a 64-bit integer but not in 32 bits.

Common mistakes

  • Returning n when it is already a palindrome.
  • Only mirroring the left half and forgetting the ± 1 and length-change candidates.
  • Breaking ties toward the larger number, or parsing into a 32-bit int.

How to talk through it

  1. 1Clarify. Is n itself allowed? Which wins on a tie? How long can n be?
  2. 2Rule out stepping. Palindromes with 18 digits can be a billion apart, so counting outward is too slow.
  3. 3Use the left half. A palindrome is set by its left half; nudge that half by −1, 0 and +1 and mirror each.
  4. 4Cover length changes. Add 9...9 with one digit fewer and 10...01 with one digit more, then pick the nearest, smaller on a tie.
  5. 5Test out loud. Try "10", "99", "1000" and a palindrome such as "11".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?