Largest Even Number

Moderate
0/80
Average time to solve is 20m
3 upvotes
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.
Detailed explanation ( Input/output format, Notes, Images )

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

Sample Input 1 :

2
1002
2242

Sample Output 1 :

2100
4222

Explanation of the Sample Input 1:

For the first test case:
Given string S = “1002”, therefore, first, swap 1(index 0) and 2(index 3) and then swap 0(index 1) and 1(index 3), which gives 2100 which is the largest number that can be formed from this string.    

For the second test case:
Swap 4(index 2) with the 2(index 0) which gives 4222 which is the largest number that can be formed from this string.  

Sample Input 2 :

2
1234        
135

Sample Output 2 :

4312
-1
Hint

Will sorting help?

Approaches (2)
Sorting the string

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.
Time Complexity

O( N*log(N) ), where N is the size of the string.

 

Since we are sorting the string and then traversing the string. O(N*log(N) + N) = O(N*log(N)). 

Space Complexity

O(1).

 

Since we are not using any extra space.

Code Solution
(100% EXP penalty)
Largest Even Number
Full screen
Console