Rearrange for Largest Even Number

Last Updated : 31 Aug, 2026

Given a string s representing an integer, rearrange its digits to form the largest possible number such that the resulting number is even. A number is even if its last digit is divisible by 2.

If it is not possible to form any even number using the digits of s, print the largest possible number formed by rearranging all digits of s (which will be an odd number).

Examples: 

Input: s = "1324"
Output: "4312"
Explanation: Largest possible even number is 4312.

Input: s = "3555"
Output: "5553"
Explanation: No even number possible, So we'll find largest odd number which is 5553.

Try It Yourself
redirect icon

[Naive Approach] Using Sorting + Greedy - O(n * log n) Time and O(n) Space

To form the largest possible number, the idea is to first arrange all digits in descending order.

However, the resulting number may end with an odd digit. To make the number as large as possible, we should use the smallest even digit available at the last position.

  • Sort the digits of s in descending order.
  • If the last digit is even, return s.
  • Otherwise, traverse the string to find the smallest even digit.
  • If no even digit exists, return the sorted string as the largest possible odd number.
  • Swap the smallest even digit with the last digit.
  • Return the resulting string.
C++
#include <bits/stdc++.h>
using namespace std;

string largestEven(string &s)
{
    // Sort all digits in descending order
    sort(s.begin(), s.end(), greater<char>());

    // If the last digit is already even,
    // the number is already the largest possible even number.
    if ((s.back() - '0') % 2 == 0)
        return s;

    // Find the smallest even digit.
    // Since the string is sorted in descending order,
    // the last even digit found will be the smallest even digit.
    int pos = -1;

    for (int i = 0; i < (int)s.size(); i++)
    {
        if ((s[i] - '0') % 2 == 0)
            pos = i;
    }

    // If no even digit exists, return the largest
    // possible number, which will be odd.
    if (pos == -1)
        return s;

    // Store the smallest even digit.
    char evenDigit = s[pos];

    // Remove it from its current position.
    s.erase(s.begin() + pos);

    // Place it at the last position.
    s.push_back(evenDigit);

    return s;
}

int main()
{
    string s = "1324";
    cout << largestEven(s) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static String largestEven(String s)
    {
        // Sort all digits in descending order
        char[] arr = s.toCharArray();
        Arrays.sort(arr);

        // Reverse the sorted array to get descending order
        for (int i = 0, j = arr.length - 1; i < j;
             i++, j--) {
            char temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }

        s = new String(arr);

        // If the last digit is already even,
        // the number is already the largest possible even
        // number.
        if ((s.charAt(s.length() - 1) - '0') % 2 == 0)
            return s;

        // Find the smallest even digit.
        // Since the string is sorted in descending order,
        // the last even digit found will be the smallest
        // even digit.
        int pos = -1;

        for (int i = 0; i < s.length(); i++) {
            if ((s.charAt(i) - '0') % 2 == 0)
                pos = i;
        }

        // If no even digit exists, return the largest
        // possible number, which will be odd.
        if (pos == -1)
            return s;

        // Store the smallest even digit.
        char evenDigit = s.charAt(pos);

        // Remove it from its current position.
        StringBuilder result = new StringBuilder(s);
        result.deleteCharAt(pos);

        // Place it at the last position.
        result.append(evenDigit);

        return result.toString();
    }

    public static void main(String[] args)
    {
        String s = "1324";
        System.out.println(largestEven(s));
    }
}
Python
def largestEven(s):
    # Sort all digits in descending order
    s = ''.join(sorted(s, reverse=True))

    # If the last digit is already even,
    # the number is already the largest possible even number.
    if (int(s[-1]) % 2 == 0):
        return s

    # Find the smallest even digit.
    # Since the string is sorted in descending order,
    # the last even digit found will be the smallest even digit.
    pos = -1

    for i in range(len(s)):
        if int(s[i]) % 2 == 0:
            pos = i

    # If no even digit exists, return the largest
    # possible number, which will be odd.
    if pos == -1:
        return s

    # Store the smallest even digit.
    evenDigit = s[pos]

    # Remove it from its current position.
    s = s[:pos] + s[pos + 1:]

    # Place it at the last position.
    s += evenDigit

    return s


# Driver Code
if __name__ == "__main__":
    s = "1324"
    print(largestEven(s))
C#
using System;

class GFG {
    static string largestEven(string s)
    {
        // Sort all digits in descending order
        char[] arr = s.ToCharArray();
        Array.Sort(arr);
        Array.Reverse(arr);

        s = new string(arr);

        // If the last digit is already even,
        // the number is already the largest possible even
        // number.
        if ((s[s.Length - 1] - '0') % 2 == 0)
            return s;

        // Find the smallest even digit.
        // Since the string is sorted in descending order,
        // the last even digit found will be the smallest
        // even digit.
        int pos = -1;

        for (int i = 0; i < s.Length; i++) {
            if ((s[i] - '0') % 2 == 0)
                pos = i;
        }

        // If no even digit exists, return the largest
        // possible number, which will be odd.
        if (pos == -1)
            return s;

        // Store the smallest even digit.
        char evenDigit = s[pos];

        // Remove it from its current position.
        s = s.Remove(pos, 1);

        // Place it at the last position.
        s += evenDigit;

        return s;
    }

    public static void Main()
    {
        string s = "1324";
        Console.WriteLine(largestEven(s));
    }
}
JavaScript
function largestEven(s)
{
    // Sort all digits in descending order
    s = s.split("").sort((a, b) => b - a).join("");

    // If the last digit is already even,
    // the number is already the largest possible even
    // number.
    if (parseInt(s[s.length - 1]) % 2 === 0)
        return s;

    // Find the smallest even digit.
    // Since the string is sorted in descending order,
    // the last even digit found will be the smallest even
    // digit.
    let pos = -1;

    for (let i = 0; i < s.length; i++) {
        if (parseInt(s[i]) % 2 === 0)
            pos = i;
    }

    // If no even digit exists, return the largest
    // possible number, which will be odd.
    if (pos === -1)
        return s;

    // Store the smallest even digit.
    let evenDigit = s[pos];

    // Remove it from its current position.
    s = s.slice(0, pos) + s.slice(pos + 1);

    // Place it at the last position.
    s += evenDigit;

    return s;
}

// Driver Code
let s = "1324";
console.log(largestEven(s));

Output
4312

[Expected Approach] Using Frequency Counting + Greedy - O(n) Time and O(1) Space

The idea is to use a frequency array to count the occurrences of each digit from 0 to 9.

To form the largest possible even number, we reserve the smallest available even digit for the last position and arrange all remaining digits in descending order.

If no even digit is present, we simply arrange all digits in descending order to get the largest possible odd number.

  • Create a frequency array freq[10] and count the occurrences of each digit.
  • Find the smallest even digit whose frequency is greater than zero.
  • If no even digit exists, arrange all digits in descending order and return the result.
  • Decrease the frequency of the selected even digit by one to reserve it for the last position.
  • Traverse digits from 9 to 0 and append them according to their frequencies.
  • Append the reserved even digit at the end and return the resulting number.
C++
#include <bits/stdc++.h>
using namespace std;

string largestEven(string &s)
{
    // Store the frequencies of all the digits
    int freq[10] = {0};

    // Count the frequency of each digit
    for (char ch : s)
        freq[ch - '0']++;

    // Find the smallest even digit
    int minEvenDigit = -1;

    for (int digit = 0; digit <= 8; digit += 2)
    {
        if (freq[digit] > 0)
        {
            minEvenDigit = digit;
            break;
        }
    }

    // If no even digit exists, return the largest
    // possible number by arranging all digits in descending order.
    if (minEvenDigit == -1)
    {
        string result;

        for (int digit = 9; digit >= 0; digit--)
        {
            while (freq[digit] > 0)
            {
                result += char(digit + '0');
                freq[digit]--;
            }
        }

        return result;
    }

    // Reserve one occurrence of the smallest even digit
    // for the last position.
    freq[minEvenDigit]--;

    string result;

    // Arrange all remaining digits in descending order
    // to maximize the number.
    for (int digit = 9; digit >= 0; digit--)
    {
        while (freq[digit] > 0)
        {
            result += char(digit + '0');
            freq[digit]--;
        }
    }

    // Place the smallest even digit at the last position.
    result += char(minEvenDigit + '0');

    return result;
}

int main()
{
    string s = "1324";
    cout << largestEven(s) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static String largestEven(String s)
    {
        // Store the frequencies of all the digits
        int[] freq = new int[10];

        // Count the frequency of each digit
        for (char ch : s.toCharArray())
            freq[ch - '0']++;

        // Find the smallest even digit
        int minEvenDigit = -1;

        for (int digit = 0; digit <= 8; digit += 2) {
            if (freq[digit] > 0) {
                minEvenDigit = digit;
                break;
            }
        }

        // If no even digit exists, return the largest
        // possible number by arranging all digits in
        // descending order.
        if (minEvenDigit == -1) {
            StringBuilder result = new StringBuilder();

            for (int digit = 9; digit >= 0; digit--) {
                while (freq[digit] > 0) {
                    result.append((char)(digit + '0'));
                    freq[digit]--;
                }
            }

            return result.toString();
        }

        // Reserve one occurrence of the smallest even digit
        // for the last position.
        freq[minEvenDigit]--;

        StringBuilder result = new StringBuilder();

        // Arrange all remaining digits in descending order
        // to maximize the number.
        for (int digit = 9; digit >= 0; digit--) {
            while (freq[digit] > 0) {
                result.append((char)(digit + '0'));
                freq[digit]--;
            }
        }

        // Place the smallest even digit at the last
        // position.
        result.append((char)(minEvenDigit + '0'));

        return result.toString();
    }

    public static void main(String[] args)
    {
        String s = "1324";
        System.out.println(largestEven(s));
    }
}
Python
def largestEven(s):
    # Store the frequencies of all the digits
    freq = [0] * 10

    # Count the frequency of each digit
    for ch in s:
        freq[ord(ch) - ord('0')] += 1

    # Find the smallest even digit
    minEvenDigit = -1

    for digit in range(0, 9, 2):
        if freq[digit] > 0:
            minEvenDigit = digit
            break

    # If no even digit exists, return the largest
    # possible number by arranging all digits in descending order.
    if minEvenDigit == -1:
        result = []

        for digit in range(9, -1, -1):
            while freq[digit] > 0:
                result.append(chr(digit + ord('0')))
                freq[digit] -= 1

        return ''.join(result)

    # Reserve one occurrence of the smallest even digit
    # for the last position.
    freq[minEvenDigit] -= 1

    result = []

    # Arrange all remaining digits in descending order
    # to maximize the number.
    for digit in range(9, -1, -1):
        while freq[digit] > 0:
            result.append(chr(digit + ord('0')))
            freq[digit] -= 1

    # Place the smallest even digit at the last position.
    result.append(chr(minEvenDigit + ord('0')))

    return ''.join(result)


# Driver Code
if __name__ == "__main__":
    s = "1324"

    print(largestEven(s))
C#
using System;
using System.Text;

class GFG {
    static string largestEven(string s)
    {
        // Store the frequencies of all the digits
        int[] freq = new int[10];

        // Count the frequency of each digit
        foreach(char ch in s) freq[ch - '0']++;

        // Find the smallest even digit
        int minEvenDigit = -1;

        for (int digit = 0; digit <= 8; digit += 2) {
            if (freq[digit] > 0) {
                minEvenDigit = digit;
                break;
            }
        }

        // If no even digit exists, return the largest
        // possible number by arranging all digits in
        // descending order.
        if (minEvenDigit == -1) {
            StringBuilder oddResult = new StringBuilder();

            for (int digit = 9; digit >= 0; digit--) {
                while (freq[digit] > 0) {
                    oddResult.Append((char)(digit + '0'));
                    freq[digit]--;
                }
            }

            return oddResult.ToString();
        }

        // Reserve one occurrence of the smallest even digit
        // for the last position.
        freq[minEvenDigit]--;

        StringBuilder result = new StringBuilder();

        // Arrange all remaining digits in descending order
        // to maximize the number.
        for (int digit = 9; digit >= 0; digit--) {
            while (freq[digit] > 0) {
                result.Append((char)(digit + '0'));
                freq[digit]--;
            }
        }

        // Place the smallest even digit at the last
        // position.
        result.Append((char)(minEvenDigit + '0'));

        return result.ToString();
    }

    public static void Main()
    {
        string s = "1324";
        Console.WriteLine(largestEven(s));
    }
}
JavaScript
function largestEven(s)
{
    // Store the frequencies of all the digits
    let freq = new Array(10).fill(0);

    // Count the frequency of each digit
    for (let ch of s)
        freq[Number(ch)]++;

    // Find the smallest even digit
    let minEvenDigit = -1;

    for (let digit = 0; digit <= 8; digit += 2) {
        if (freq[digit] > 0) {
            minEvenDigit = digit;
            break;
        }
    }

    // If no even digit exists, return the largest
    // possible number by arranging all digits in descending
    // order.
    if (minEvenDigit === -1) {
        let result = [];

        for (let digit = 9; digit >= 0; digit--) {
            while (freq[digit] > 0) {
                result.push(String(digit));
                freq[digit]--;
            }
        }

        return result.join("");
    }

    // Reserve one occurrence of the smallest even digit
    // for the last position.
    freq[minEvenDigit]--;

    let result = [];

    // Arrange all remaining digits in descending order
    // to maximize the number.
    for (let digit = 9; digit >= 0; digit--) {
        while (freq[digit] > 0) {
            result.push(String(digit));
            freq[digit]--;
        }
    }

    // Place the smallest even digit at the last position.
    result.push(String(minEvenDigit));

    return result.join("");
}

// Driver Code
let s = "1324";
console.log(largestEven(s));

Output
4312
Comment