KatInterview

Find Next Larger Palindrome Within Digit Limit

StringsAuto-graded · 27 test cases
HardAuto-gradedStringspalindromesstring-manipulationgreedy

Last updated

Tests constructing the immediate successor palindrome by manipulating the left half, handling carries, length transitions, and an upper bound.

You are given a positive integer represented as a string. Your task is to find the smallest palindrome that is strictly larger than the given number. However, the result must not exceed 18 digits in length. If no valid palindrome exists within this constraint, return the original number unchanged.

A palindrome reads identically forwards and backwards. For instance, 121, 7, and 90409 are palindromes.

Write a function that takes a decimal string and returns the next palindrome as a string, subject to the 18-digit limit.

Rules

  • The input has no leading zeros and represents an integer from 1 to 999999999999999999 (18 nines).
  • The output must be strictly greater than the input, even if the input is already a palindrome.
  • If the smallest palindrome above the input would require 19 or more digits, return the input unchanged.
  • Return the result as a string with no leading zeros.

Constraints

  • 1 <= len(n) <= 18
  • n consists only of digits '0' through '9' with no leading zeros
  • The input value is in the range [1, 10^18 - 1]
  • Numbers may exceed typical integer limits in some languages, so work with strings
  • The distance to the answer can be very large, so brute-force enumeration will time out

Examples

Example 1

Input: find_next_palindrome('12932')

Output: '13031'

Example 2

Input: find_next_palindrome('99')

Output: '101'

Example 3

Input: find_next_palindrome('999999999999999999')

Output: '999999999999999999'

Hints

Hint 1

A palindrome's structure is fully determined by its first half—the remaining digits mirror it back.

Hint 2

Try building a palindrome by keeping the input's left half and reflecting it. If that's not large enough, increment the left half by one.

Hint 3

When the left half is all 9s (like 99 or 999), incrementing it produces a longer number. The shortest palindrome with one more digit is 10...01.