Open In App

Largest palindromic number by permuting digits

Last Updated : 20 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
C++
// CPP program to print the largest palindromic
// number by permuting digits of a number
#include <bits/stdc++.h>
using namespace std;
 
// function to check if a number can be
// permuted to form a palindrome number
bool possibility(vector<int> &cnt) {
    
    // counts the occurrence of number which is odd
    int countodd = 0;
    for (int i = 0; i < 10; i++) {

        // if occurrence is odd
        if (cnt[i] & 1)
            countodd++;
 
    }
 
    // If atmost 1 odd occurrence is 
    // present, return true.
    return countodd <= 1;
}
 
// function to print the largest palindromic number
// by permuting digits of a number
string largestPalindrome(string s) {
 
    // string length
    int n = s.length();
 
    // map that count the occurrence of digits 
    vector<int> cnt(10, 0);
    for (int i = 0; i < n; i++)
        cnt[s[i] - '0']++;
 
    // check the possibility of a palindromic number
    if (possibility(cnt) == false) {
        return "";
    }
 
    // integer array that stores the largest
    // permuted palindromic number
    vector<int> largest(n);
 
    // pointer of front
    int front = 0;
 
    // greedily start from 9 to 0 and place the
    // greater number in front and odd in the
    // middle
    for (int i = 9; i >= 0; i--) {
 
        // if the occurrence of number is odd
        if (cnt[i] & 1) {
 
            // place one odd occurring number
            // in the middle
            largest[n / 2] = i;
 
            // decrease the count
            cnt[i]--;
        }
        

        // if all numbers occur even times,
        // then place greedily
        while (cnt[i] > 0) {

            // place greedily at front
            largest[front] = i;
            largest[n - front - 1] = i;

            // 2 numbers are placed, so 
            // decrease the count
            cnt[i] -= 2;

            // increase placing position
            front++;
        }
        
    }
 
    // Store the palindrome in a string
    string res = "";
    for (int i=0; i<n; i++) res.push_back('0'+largest[i]);
    
    return res;
}
 
int main() {
    string s = "313551";
    string res = largestPalindrome(s);
    cout << res;
    return 0;
}
Java
// Java program to print the largest palindromic
// number by permuting digits of a number

import java.util.Arrays;

class GfG {

    // function to check if a number can be
    // permuted to form a palindrome number
    static boolean possibility(int[] cnt) {
        
        // counts the occurrence of number which is odd
        int countodd = 0;
        for (int i = 0; i < 10; i++) {

            // if occurrence is odd
            if ((cnt[i] & 1) == 1)
                countodd++;
 
        }
 
        // If atmost 1 odd occurrence is 
        // present, return true.
        return countodd <= 1;
    }

    // function to print the largest palindromic number
    // by permuting digits of a number
    static String largestPalindrome(String s) {

        // string length
        int n = s.length();

        // map that count the occurrence of digits 
        int[] cnt = new int[10];
        Arrays.fill(cnt, 0);
        for (int i = 0; i < n; i++)
            cnt[s.charAt(i) - '0']++;

        // check the possibility of a palindromic number
        if (!possibility(cnt)) {
            return "";
        }

        // integer array that stores the largest
        // permuted palindromic number
        int[] largest = new int[n];

        // pointer of front
        int front = 0;

        // greedily start from 9 to 0 and place the
        // greater number in front and odd in the
        // middle
        for (int i = 9; i >= 0; i--) {

            // if the occurrence of number is odd
            if ((cnt[i] & 1) == 1) {

                // place one odd occurring number
                // in the middle
                largest[n / 2] = i;

                // decrease the count
                cnt[i]--;
            }

            // if all numbers occur even times,
            // then place greedily
            while (cnt[i] > 0) {

                // place greedily at front
                largest[front] = i;
                largest[n - front - 1] = i;

                // 2 numbers are placed, so decrease the count
                cnt[i] -= 2;

                // increase placing position
                front++;
            }
        }

        // Store the palindrome in a string
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < n; i++) 
            res.append((char) ('0' + largest[i]));

        return res.toString();
    }

    public static void main(String[] args) {
        String s = "313551";
        String res = largestPalindrome(s);
        System.out.println(res);
    }
}
Python
# Python program to print the largest palindromic
# number by permuting digits of a number

# function to check if a number can be
# permuted to form a palindrome number
def possibility(cnt):
    
    # counts the occurrence of number which is odd
    countodd = 0
    for i in range(10):

        # if occurrence is odd
        if cnt[i] & 1:
            countodd += 1

    # If atmost 1 odd occurrence is 
    # present, return true.
    return countodd <= 1

# function to print the largest palindromic number
# by permuting digits of a number
def largestPalindrome(s):

    # string length
    n = len(s)

    # map that count the occurrence of digits 
    cnt = [0] * 10
    for i in range(n):
        cnt[int(s[i])] += 1

    # check the possibility of a palindromic number
    if not possibility(cnt):
        return ""

    # integer array that stores the largest
    # permuted palindromic number
    largest = [0] * n

    # pointer of front
    front = 0

    # greedily start from 9 to 0 and place the
    # greater number in front and odd in the
    # middle
    for i in range(9, -1, -1):

        # if the occurrence of number is odd
        if cnt[i] & 1:

            # place one odd occurring number
            # in the middle
            largest[n // 2] = i

            # decrease the count
            cnt[i] -= 1

        # if all numbers occur even times,
        # then place greedily
        while cnt[i] > 0:

            # place greedily at front
            largest[front] = i
            largest[n - front - 1] = i

            # 2 numbers are placed, so decrease the count
            cnt[i] -= 2

            # increase placing position
            front += 1

    # Store the palindrome in a string
    return "".join(str(num) for num in largest)

if __name__ == "__main__":
    s = "313551"
    res = largestPalindrome(s)
    print(res)
C#
// C# program to print the largest palindromic
// number by permuting digits of a number

using System;

class GfG {

    // function to check if a number can be
    // permuted to form a palindrome number
    static bool possibility(int[] cnt) {
        
        // counts the occurrence of number which is odd
        int countodd = 0;
        for (int i = 0; i < 10; i++) {

            // if occurrence is odd
            if ((cnt[i] & 1) == 1)
                countodd++;
        }
 
        // If atmost 1 odd occurrence is 
        // present, return true.
        return countodd <= 1;
    }

    // function to print the largest palindromic number
    // by permuting digits of a number
    static string largestPalindrome(string s) {

        // string length
        int n = s.Length;

        // map that count the occurrence of digits 
        int[] cnt = new int[10];
        for (int i = 0; i < n; i++)
            cnt[s[i] - '0']++;

        // check the possibility of a palindromic number
        if (!possibility(cnt)) {
            return "";
        }

        // integer array that stores the largest
        // permuted palindromic number
        int[] largest = new int[n];

        // pointer of front
        int front = 0;

        // greedily start from 9 to 0 and place the
        // greater number in front and odd in the
        // middle
        for (int i = 9; i >= 0; i--) {

            // if the occurrence of number is odd
            if ((cnt[i] & 1) == 1) {

                // place one odd occurring number
                // in the middle
                largest[n / 2] = i;

                // decrease the count
                cnt[i]--;
            }

            // if all numbers occur even times,
            // then place greedily
            while (cnt[i] > 0) {

                // place greedily at front
                largest[front] = i;
                largest[n - front - 1] = i;

                // 2 numbers are placed, so decrease the count
                cnt[i] -= 2;

                // increase placing position
                front++;
            }
        }

        // Store the palindrome in a string
        return string.Join("", largest);
    }

    static void Main() {
        string s = "313551";
        string res = largestPalindrome(s);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to print the largest palindromic
// number by permuting digits of a number

// function to check if a number can be
// permuted to form a palindrome number
function possibility(cnt) {
    
    // counts the occurrence of number which is odd
    let countodd = 0;
    for (let i = 0; i < 10; i++) {

        // if occurrence is odd
        if (cnt[i] & 1)
            countodd++;
    }

    // If at most 1 odd occurrence is 
    // present, return true.
    return countodd <= 1;
}

// function to print the largest palindromic number
// by permuting digits of a number
function largestPalindrome(s) {
    // Similar logic as C++ implementation
    let n = s.length;
    let cnt = Array(10).fill(0);
    for (let ch of s) cnt[ch - '0']++;

    if (!possibility(cnt)) return "";

    let largest = Array(n);
    let front = 0;

    for (let i = 9; i >= 0; i--) {
        if (cnt[i] & 1) {
            largest[Math.floor(n / 2)] = i;
            cnt[i]--;
        }
        while (cnt[i] > 0) {
            largest[front] = i;
            largest[n - front - 1] = i;
            cnt[i] -= 2;
            front++;
        }
    }
    return largest.join("");
}

console.log(largestPalindrome("313551"));

Output
531135

Next Article

Similar Reads