![]() |
VOOZH | about |
Given a very large integer n in the form of string, the task is to return the largest palindromic number obtainable by permuting the digits of n. If it is not possible to make a palindromic number, then return an empty string.
Examples :
Input : "313551"
Output : "531135"
Explanations : 531135 is the largest number which is a palindrome. 135531, 315513 and other numbers can also be formed but we need the largest of all of the palindromes.
Input : "331"
Output : "313"
Explanation: 313 is the only possible palindrome.
Input : "3444"
Output : ""
Explanation: Palindrome is not possible.
The naive approach will be to try all the permutations possible, and print the largest of such combinations, which is a palindrome.
The idea is to create the largest possible palindrome by placing the larger digits in the more significant positions and ensuring the palindrome property is maintained.
This greedy approach works because to maximize the numerical value of a palindrome, we want to place the largest available digits at the most significant positions, then the next largest digits in the next positions, and so on. Since palindromes must read the same from both ends, we need to place the same digit at corresponding positions from both ends, and can only have at most one digit that occurs an odd number of times (which would be placed in the middle).
Step by step approach:
531135