Largest Even Number

Posted: 8 Mar, 2021
Difficulty: Moderate


Try Problem

You are given a string ‘S’. Your task is to find the largest even number that can be formed by rearranging string S’s digits.


In case the string does not contain any even digit, then return -1.

For example,

Given string SS = “21”
The output will be 12 since it is the largest even number is formed by swapping 2 and 1.

Input format :

The first line of input contains an integer T denoting the number of test cases.

The first and the only line of each test case contains a single string ‘S’.

Output format :

For each test case, return the max possible even number that can be formed. The output of each test case will be printed in a separate line.


You do not need to print anything. It has already been taken care of. Just implement the given function.


1 <= T <= 5
1 <= |S| <= 3000
0 <= S[i] <= 9

Where |S| denotes the length of the given string 'S'.

Time Limit: 1 sec
Approach 1

The main idea is to sort the string in descending order, then put the minimum even number at the last position. If no even number is present, then put the minimum number at the last position.


  • Sort the string in descending order.
  • Loop from the ‘N-1’ index, and the first time we find an even number, swap it to the number at ‘N-1’th index.
  • Break the loop after the swap.
  • Loop from 0th index to ‘N-2’th index to make sure S[i] > S[i+1], if not swap S[i] and S[i+1].
  • Return the resulting string.
Try Problem