Last Updated: 8 Mar, 2021

Largest Even Number

Moderate
Asked in companies
Goldman SachsSnapdeal Ltd.

Problem statement

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.

Note:

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.

Note:

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

Constraints:

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

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

Time Limit: 1 sec

Approaches

01 Approach

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.

02 Approach

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.

Sorting can be done in linear time using a frequency array for the digits of the number as the number of distinct elements that are needed to be sorted can be at most 10 because it contains digits between 0 - 9 only in the worst case.

 

  • Create a frequency table FREQ[10] which stores the occurrences of each number in the string.
  • Find the smallest even number and decrease its FREQ by 1 in the FREQ array.
  • Traverse the FREQ array in reverse order.
  • Add the frequency of each number in the result string.
  • Add the smallest even number at the end.
  • Return the resulting string.