KatInterview

Smallest Palindrome Above a Given Number

Math & Bit ManipulationAuto-graded · 24 test cases
MediumAuto-gradedMath & Bit Manipulationpalindromedigitsmath

Last updated

Find the smallest palindromic integer strictly larger than a non-negative integer, using the left half of the digits and carry handling, including the all-9s case.

Next Larger Palindrome

A non-negative integer is a palindrome if its decimal representation (with no leading zeros) reads the same forwards and backwards. Single-digit numbers, including 0, are palindromes.

You are given a non-negative integer n. Return the smallest palindromic integer that is strictly greater than n.

Details

  • The result must be strictly greater than n, so if n is already a palindrome you must still move to a larger one.
  • The answer may have more digits than n. For example, if n consists only of 9s, the answer is longer.
  • Return the answer as an integer.
  • Aim for a solution that runs in time proportional to the number of digits of n, rather than testing n + 1, n + 2, and so on one at a time.

Constraints

  • n is an integer with n >= 0.
  • n fits comfortably in standard integer arithmetic (Python integers are unbounded, but treat the digit count d as the measure of input size).
  • The function returns a single integer.

Examples

Example 1

Input: next_larger_palindrome(121)

Output: 131

Example 2

Input: next_larger_palindrome(99)

Output: 101

Example 3

Input: next_larger_palindrome(8)

Output: 9

Hints

Hint 1

A palindrome is completely determined by its first half (the first ceil(d/2) digits). The second half is just a mirror of it.

Hint 2

Mirror the left half of n onto its right half. If that gives a number strictly larger than n, it is already the answer. Otherwise you need the next larger left half.

Hint 3

To get the next left half, add 1 starting at the middle digit and carry leftward, then mirror again. If the carry escapes past the leading digit, n was all 9s and the answer is 1, then zeros, then 1, with d+1 digits.