Smallest Palindrome Above a Given Number
Math & Bit ManipulationAuto-graded · 24 test casesLast 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 ifnis already a palindrome you must still move to a larger one. - The answer may have more digits than
n. For example, ifnconsists 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 testingn + 1,n + 2, and so on one at a time.
Constraints
nis an integer withn >= 0.nfits comfortably in standard integer arithmetic (Python integers are unbounded, but treat the digit countdas 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A palindrome with d digits is fixed by its left half, the first ceil(d/2) digits; the right half is the mirror image. So we reason about left halves rather than scanning numbers one by one.
- Extract the digits of
n(use[0]whennis0). - Build
candidateby copying the left half onto the right half in mirrored order. - If
candidate > n, return it. Nothing smaller with the same left half or a smaller one can beat it. - Otherwise, add 1 to the left half. Start at the middle digit (index
(d-1)//2), turn 9s into 0s while carrying leftward, and add 1 to the first non-9 digit. Then mirror again. - If the carry runs past the first digit, every digit in the left half was 9, which implies
nwas all 9s. The answer is1, thend-1zeros, then1(a(d+1)-digit number).
Why it is correct
Take any d-digit palindrome P with left half L', and let L be the left half of n.
- If
L' < L, thenP < n, so it is not allowed. - If
L' = L, thenPis exactly the mirror ofL. It is valid only if it exceedsn. - If
L' > L, thenP > n, and a smallerL'gives a smallerP, so the best choice isL + 1.
So the answer is the mirror of L if it is strictly larger than n, and otherwise the mirror of L + 1. If L + 1 needs an extra digit, then L was all 9s, the mirror was 99...9, and since it was not larger than n, n itself is 99...9. No d-digit palindrome is larger, and the smallest (d+1)-digit palindrome is 10...01.
The list comparison candidate <= digits is valid because both lists have the same length, so lexicographic order equals numeric order. The comparison is non-strict so that a palindromic n forces the increment path.
Complexity
- Time: O(d), where
dis the number of digits ofn. Extraction, mirroring, carry propagation and rebuilding are each linear passes. - Space: O(d) for the digit lists.
Reference solution
def next_larger_palindrome(n: int) -> int:
digits = []
x = n
if x == 0:
digits.append(0)
else:
while x:
digits.append(x % 10)
x //= 10
digits.reverse()
m = len(digits)
candidate = digits[:]
# Mirror the left half onto the right half.
for i in range(m // 2):
candidate[m - 1 - i] = candidate[i]
# If the mirrored value is not strictly larger, increment the left half.
if candidate <= digits:
i = (m - 1) // 2
while i >= 0 and candidate[i] == 9:
candidate[i] = 0
i -= 1
if i < 0:
# All 9s: 9 -> 11, 99 -> 101, 999 -> 1001.
candidate = [1] + [0] * (m - 1) + [1]
else:
candidate[i] += 1
for j in range(m // 2):
candidate[m - 1 - j] = candidate[j]
result = 0
for digit in candidate:
result = result * 10 + digit
return result