Next Palindrome Using Same Digits - Problem

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.

Input & Output

Example 1 — Basic Increment
$ Input: num = "12321"
Output: "13031"
💡 Note: Next permutation of left half "123" is "130". Mirroring gives "13031" which is the smallest palindrome larger than "12321".
Example 2 — All 9s
$ Input: num = "99"
Output: ""
💡 Note: No larger palindrome can be formed using the same digits since both digits are already maximum (9).
Example 3 — Single Digit
$ Input: num = "1"
Output: ""
💡 Note: Only one digit available and it's not the maximum, but no larger single-digit palindrome exists using same digit.

Constraints

  • 1 ≤ num.length ≤ 105
  • num consists of only digits
  • num represents a valid palindrome

Visualization

Tap to expand
Next Palindrome Using Same Digits INPUT Original Palindrome: 1 2 3 2 1 0 1 2 3 4 Extract First Half: 1 2 3 Half = "12" (middle excluded) Input: num = "12321" ALGORITHM STEPS 1 Take First Half half = "12" 2 Next Permutation "12" ---> "21" 1 2 --> 2 1 3 Handle Middle Middle = "0" (smallest) 4 Mirror to Build "21" + "0" + "12" = "21012" 2 1 0 1 2 Adjust: "21012" invalid, use "13031" FINAL RESULT Next Palindrome: 1 3 0 3 1 Verification: 12321 (original) 13031 (result) OK Is Palindrome? "13031" reversed = "13031" OK - Valid Palindrome Output: "13031" Key Insight: For palindromes, we only need to find the next permutation of the first half. Then mirror it to create the full palindrome. Handle odd-length by keeping middle digit as the smallest possible value. Time: O(n), Space: O(n) where n = length of number. TutorialsPoint - Next Palindrome Using Same Digits | Next Permutation on Half Approach
Asked in
Google 35 Amazon 28 Facebook 22 Microsoft 18
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen