Find Next Larger Palindrome Within Digit Limit
StringsAuto-graded · 27 test casesLast 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) <= 18nconsists 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that a palindrome is completely defined by its leading digits. For a number with L digits, the first ceil(L / 2) digits determine the entire palindrome—the remaining digits are just the mirror image.
This means we only need to consider two candidates of the same length:
- Keep the existing left half: Extract the left half from the input, mirror it to form a palindrome, and check if it's larger than the input.
- Increment the left half: If the first candidate isn't large enough, add one to the left half and mirror it.
If incrementing the left half causes it to grow in length (for example, incrementing 99 gives 100), then the original number was all 9s. In this case, the next palindrome has L + 1 digits and takes the form 10...01 (a 1, then L - 1 zeros, then another 1).
Finally, we verify that the result doesn't exceed 18 digits. Only when the input is exactly 18 nines does the result exceed the limit, in which case we return the input unchanged.
Why It Works
Among all palindromes of length L, lexicographic order matches the order of their left halves. A palindrome with a larger left half is always greater overall because the left half occupies the most significant positions.
Since we want the smallest palindrome strictly above the input, we start with the input's own left half. If mirroring it produces something too small (or equal), we try the very next left half. Any left half beyond that would yield a larger palindrome, so there's no need to search further.
Edge cases are handled naturally:
- If the input is already a palindrome, mirroring its left half reproduces the input, which isn't strictly greater, so we increment.
- When the left half is all 9s, incrementing produces a carry into a new digit, triggering the length-increase logic.
- The 18-digit boundary is explicitly checked.
Complexity
- Time: O(L), where L is the number of digits. We slice the string, increment an integer, reverse a substring, and perform comparisons—all linear in the length. Since L ≤ 18, this is effectively constant time.
- Space: O(L) for storing intermediate strings.
Brute force (testing each number above the input) would fail because the gap to the next palindrome can exceed 10^9 iterations.
def find_next_palindrome(n: str) -> str:
length = len(n)
MAX_VALUE = 10 ** 18 - 1
original_value = int(n)
def build_palindrome(left_half: int, total_length: int) -> str:
"""Construct a palindrome by mirroring the left half."""
left_str = str(left_half)
if total_length % 2 == 1:
# Odd length: exclude the middle digit when reversing
return left_str + left_str[-2::-1]
else:
# Even length: reverse the entire left half
return left_str + left_str[::-1]
# Determine how many digits form the "left half" (including middle for odd lengths)
half_size = (length + 1) // 2
left_half = int(n[:half_size])
# First candidate: mirror the existing left half
candidate = build_palindrome(left_half, length)
if int(candidate) > original_value:
return candidate
# Second candidate: increment the left half and mirror
left_half += 1
if len(str(left_half)) == half_size:
# The increment didn't add a digit
candidate = build_palindrome(left_half, length)
else:
# The left half overflowed (was all 9s), so we need one more digit
candidate = '1' + '0' * (length - 1) + '1'
# Check the 18-digit constraint
if int(candidate) > MAX_VALUE:
return n
return candidate