VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-palindromic-number-permuting-digits/

⇱ Largest palindromic number by permuting digits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest palindromic number by permuting digits

Last Updated : 11 Jul, 2025

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.

[Naive Approach] Try All Permutations

The naive approach will be to try all the permutations possible, and print the largest of such combinations, which is a palindrome. 

[Efficient Approach] Using Greedy Method - O(n) time and O(n) space

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:

  1. Check if forming a palindrome is possible by counting digit occurrences and ensuring at most one digit appears an odd number of times.
  2. If possible, initialize an array to store the result and start placing digits from the outside in.
  3. For any digit that appears an odd number of times, place one occurrence in the middle position.
  4. Working from 9 down to 0, place matching pairs of each digit symmetrically from the outside inward.
  5. Convert the resulting array back to a string representation of the largest possible palindrome.

Output
531135
Comment
Article Tags: