This problem asks to find the smallest palindrome greater than a given numeric string num
using only the digits present in num
. The solution leverages the concept of finding the next permutation.
Approach:
Focus on the First Half: Since the input num
is already a palindrome, we only need to consider the first half of the digits. Any change to the first half will automatically determine the second half due to the palindrome requirement.
Find the Next Permutation: The core logic is to find the next lexicographically larger permutation of the digits in the first half. This is done using the standard next permutation algorithm. If no such permutation exists (meaning the digits are already in descending order), it indicates that no larger palindrome can be formed using the given digits.
Construct the Palindrome: Once the next permutation of the first half is found, the second half is simply mirrored from the first half to create the resulting palindrome.
Algorithm: (Next Permutation)
The next permutation algorithm works as follows:
Find the largest index i
such that nums[i] < nums[i+1]
. This identifies a digit that can be swapped to create a larger permutation.
If no such index is found, the digits are already in descending order, and there is no larger permutation.
Find the largest index j
such that nums[j] > nums[i]
.
Swap nums[i]
and nums[j]
.
Reverse the subarray nums[i+1:]
. This step ensures that the remaining digits are arranged in ascending order to create the smallest larger permutation.
Time and Space Complexity:
Time Complexity: O(n), where n is the length of the input string. This is because the next permutation algorithm and the palindrome construction both take linear time.
Space Complexity: O(n) in the worst case, mainly due to creating a copy of the input string (in some implementations). In-place modification is possible, reducing space complexity to O(1), but may make the code more complex.
Code Explanation (Python):
class Solution:
def nextPalindrome(self, num: str) -> str:
def next_permutation(nums: List[str]) -> bool:
n = len(nums) // 2 # Consider only the first half
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i < 0: # No larger permutation possible
return False
j = n - 1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i] # Swap
nums[i + 1 : n] = nums[i + 1 : n][::-1] # Reverse
return True
nums = list(num)
if not next_permutation(nums):
return "" # No solution
n = len(nums)
for i in range(n // 2):
nums[n - 1 - i] = nums[i] # Mirror the first half
return "".join(nums)
The other language implementations follow a similar structure, adapting the next permutation algorithm and palindrome construction to the specifics of each language. The core logic remains consistent across all solutions.