LeetCode 1842. Next Palindrome Using Same Digits Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1842. Next Palindrome Using Same Digits

Description

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 <= 105
  • num is a palindrome.

Solutions

Solution 1: Find the Next Permutation of the First Half

According to the problem description, we only need to find the next permutation of the first half of the string, then traverse the first half and symmetrically assign values to the second half.

The time complexity is O(n), and the space complexity is O(n). Where n is the length of the string.

PythonJavaC++GoTypeScript
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)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !