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 Digits12321Input: "12321"Apply Next Permutation to Left Half13031Output: "13031"Mirror left half to right half🎯 **Key Insight:** Work only on left half, then mirror for efficiency!
Understanding the Visualization
1
Input Palindrome
Given palindrome string that reads same forwards/backwards
2
Find Next Pattern
Use next permutation on left half to find next larger arrangement
3
Mirror Result
Create complete palindrome by mirroring left half to right
Key Takeaway
🎯 Key Insight: Only need to find next permutation of left half, then mirror to create complete palindrome
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