Talentd
FleetCode

1842. Next Palindrome Using Same Digits

Hard54.2% acceptance1 companyPremium elsewhere, free here

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.

Asked at 1 company

Hints open one at a time

Hint 1
Is it possible to swap one character in the first half of the palindrome to make the next one?
Hint 2
Are there different cases for when the length is odd and even?
25:47
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
"1221"
Input
"32123"
Input
"45544554"
Your code is saved on this device.Solution