Next Palindrome Using Same Digits Problem
Description
LeetCode Problem 1842.
You are given a numeric string num, representing a very large palindrome.
Return *the smallest palindrome larger than *num that can be created by rearranging its digits. If no such palindrome exists, return an empty string "".
A palindrome is a number that reads the same backward as forward.
Example 1:
Input: num = "1221"
Output: "2112"
Explanation: The next palindrome larger than "1221" is "2112".
Example 2:
Input: num = "32123"
Output: ""
Explanation: No palindromes larger than "32123" can be made by rearranging the digits.
Example 3:
Input: num = "45544554"
Output: "54455445"
Explanation: The next palindrome larger than "45544554" is "54455445".
Constraints:
1 <= num.length <= 10^5numis a palindrome.
Solution
Approach: Next Permutation of the First Half
A palindrome is determined by its first half, and rearranging the digits into a larger palindrome means rearranging the first half into a larger arrangement. So compute the next permutation of the first half (the middle digit of an odd-length number stays put). If there is none, return an empty string.
Otherwise mirror the new first half onto the second half.
Complexity: O(n) time and O(n) space, where n is the length of the string.
class Solution:
def nextPalindrome(self, num: str) -> str:
def next_permutation(nums: List[str]) -> bool:
n = len(nums) // 2
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i < 0:
return False
j = n - 1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1 : n] = nums[i + 1 : n][::-1]
return True
nums = list(num)
if not next_permutation(nums):
return ""
n = len(nums)
for i in range(n // 2):
nums[n - i - 1] = nums[i]
return "".join(nums)