Given an odd number in the form of string, the task is to make largest even number possible from the given number provided one is allowed to do exactly only one swap operation, if no such number is possible then return the input string itself.
Examples :
Input: s = 4543
Output: 4534
Explanation: Swap second 4 and 3.
Input: s = 1539
Output: 1539
Explanation: No even no. present.
Table of Content
[Naive Approach] Try Every Possible Even Digit Swap - O(n ^ 2) Time and O(n) Space
The idea is to try swapping the last digit (which is odd) with every even digit present before it. After each swap, check whether the resulting number is even and keep the largest possible number obtained. Finally, return the best result. If no even digit exists, return the original string.
Working of Approach:
- Try swapping the last digit with every even digit present in the string.
- After each swap, compare the obtained number with res and store the largest valid result.
- Restore the original string after every swap and return res as the final answer.
#include <iostream>
#include <string>
#include <utility>
using namespace std;
string makeEven(string &s)
{
int n = s.length();
string res = "";
// Try every possible swap
for (int i = 0; i < n - 1; i++)
{
// Swap only with even digit
if ((s[i] - '0') % 2 == 0)
{
swap(s[i], s[n - 1]);
// Store the largest valid even number
if (res == "" || s > res)
res = s;
// Restore original string
swap(s[i], s[n - 1]);
}
}
// If no valid swap is possible
if (res == "")
return s;
return res;
}
int main()
{
string s = "4543";
cout << makeEven(s);
return 0;
}
import java.util.Collections;
public class Main {
public static String makeEven(String s) {
int n = s.length();
String res = "";
// Try every possible swap
for (int i = 0; i < n - 1; i++) {
// Swap only with even digit
if ((s.charAt(i) - '0') % 2 == 0) {
char[] sArr = s.toCharArray();
swap(sArr, i, n - 1);
s = new String(sArr);
// Store the largest valid even number
if (res.equals("") || s.compareTo(res) > 0)
res = s;
// Restore original string
swap(sArr, i, n - 1);
s = new String(sArr);
}
}
// If no valid swap is possible
if (res.equals(""))
return s;
return res;
}
private static void swap(char[] arr, int i, int j) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
String s = "4543";
System.out.println(makeEven(s));
}
}
def makeEven(s):
n = len(s)
res = ""
# Try every possible swap
for i in range(n - 1):
# Swap only with even digit
if (int(s[i]) % 2 == 0):
s_list = list(s)
s_list[i], s_list[n - 1] = s_list[n - 1], s_list[i]
s = ''.join(s_list)
# Store the largest valid even number
if res == "" or s > res:
res = s
# Restore original string
s_list[i], s_list[n - 1] = s_list[n - 1], s_list[i]
s = ''.join(s_list)
# If no valid swap is possible
if res == "":
return s
return res
if __name__ == '__main__':
s = "4543"
print(makeEven(s))
using System;
public class Program
{
public static string makeEven(string s)
{
int n = s.Length;
string res = "";
// Try every possible swap
for (int i = 0; i < n - 1; i++)
{
// Swap only with even digit
if ((s[i] - '0') % 2 == 0)
{
char[] sArr = s.ToCharArray();
swap(sArr, i, n - 1);
s = new string(sArr);
// Store the largest valid even number
if (res == "" || string.Compare(s, res) > 0)
res = s;
// Restore original string
swap(sArr, i, n - 1);
s = new string(sArr);
}
}
// If no valid swap is possible
if (res == "")
return s;
return res;
}
private static void swap(char[] arr, int i, int j)
{
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void Main()
{
string s = "4543";
Console.WriteLine(makeEven(s));
}
}
function makeEven(s) {
let n = s.length;
let res = "";
// Try every possible swap
for (let i = 0; i < n - 1; i++) {
// Swap only with even digit
if ((s.charCodeAt(i) - '0'.charCodeAt(0)) % 2 === 0) {
let sArr = s.split('');
[sArr[i], sArr[n - 1]] = [sArr[n - 1], sArr[i]];
s = sArr.join('');
// Store the largest valid even number
if (res === "" || s > res)
res = s;
// Restore original string
[sArr[i], sArr[n - 1]] = [sArr[n - 1], sArr[i]];
s = sArr.join('');
}
}
// If no valid swap is possible
if (res === "")
return s;
return res;
}
let s = "4543";
console.log(makeEven(s));
Output
4534
[Expected Approach] Greedy One Pass - O(n) Time and O(1) Space
The idea is to traverse the string once and find the best even digit to swap with the last odd digit. If an even digit smaller than or equal to the last digit is found, swap it immediately. Otherwise, swap with the rightmost even digit. If no even digit exists, return the original string.
Let us understand with an example:
- For s = "4543", the last digit is 3. Traverse the string and find the nearest even digit.
- At index 0, digit 4 is even. Since 4 > 3, continue searching.
- At index 1, digit 5 is odd. At index 2, digit 4 is even and 4 > 3, so choose this digit.
- Swap 4 at index 2 with the last digit 3 to get "4534", which is the largest possible even number.
#include <iostream>
#include <string>
#include <utility>
#include <climits>
using namespace std;
// Function to make the string even by swapping the last digit
// with the nearest even // digit
string makeEven(string &s)
{
int n = s.length();
int even = INT_MAX, index;
// Iterating through the string to find an even digit
for (int i = 0; i < n - 1; i++)
{
if ((s[i] - '0') % 2 == 0)
{
even = (s[i] - '0');
index = i;
}
// Checking if the even digit found is smaller than the last digit
if (even <= (s[n - 1] - '0'))
break;
}
// If no even digit is found, return the original string
if (even == INT_MAX)
return s;
// Swapping the even digit with the last digit
swap(s[index], s[n - 1]);
return s; // Return the modified string
}
int main()
{
string s = "4543";
cout << makeEven(s);
return 0;
}
import java.util.Collections;
public class Main {
// Function to make the string even by swapping the last digit with the nearest even
// digit
public static String makeEven(String s) {
int n = s.length();
int even = Integer.MAX_VALUE;
int index = -1;
// Iterating through the string to find an even digit
for (int i = 0; i < n - 1; i++) {
if ((s.charAt(i) - '0') % 2 == 0) {
even = s.charAt(i) - '0';
index = i;
}
// Checking if the even digit found is smaller than the last digit
if (even <= (s.charAt(n - 1) - '0'))
break;
}
// If no even digit is found, return the original string
if (even == Integer.MAX_VALUE)
return s;
// Swapping the even digit with the last digit
char[] charArray = s.toCharArray();
char temp = charArray[index];
charArray[index] = charArray[n - 1];
charArray[n - 1] = temp;
return new String(charArray); // Return the modified string
}
public static void main(String[] args) {
String s = "4543";
System.out.println(makeEven(s));
}
}
"""
Function to make the string even by swapping the last digit with the nearest even
digit
"""
def makeEven(s):
n = len(s)
even = float('inf')
index = -1
# Iterating through the string to find an even digit
for i in range(n - 1):
if (int(s[i]) % 2 == 0):
even = int(s[i])
index = i
# Checking if the even digit found is smaller than the last digit
if even <= (int(s[n - 1])):
break
# If no even digit is found, return the original string
if even == float('inf'):
return s
# Swapping the even digit with the last digit
s_list = list(s)
s_list[index], s_list[n - 1] = s_list[n - 1], s_list[index]
return ''.join(s_list) # Return the modified string
s = "4543"
print(makeEven(s))
using System;
class Program {
// Function to make the string even by swapping the last digit with the nearest even
// digit
static string makeEven(string s) {
int n = s.Length;
int even = int.MaxValue;
int index = -1;
// Iterating through the string to find an even digit
for (int i = 0; i < n - 1; i++) {
if ((s[i] - '0') % 2 == 0) {
even = s[i] - '0';
index = i;
}
// Checking if the even digit found is smaller than the last digit
if (even <= (s[n - 1] - '0'))
break;
}
// If no even digit is found, return the original string
if (even == int.MaxValue)
return s;
// Swapping the even digit with the last digit
char[] charArray = s.ToCharArray();
char temp = charArray[index];
charArray[index] = charArray[n - 1];
charArray[n - 1] = temp;
return new string(charArray); // Return the modified string
}
static void Main() {
string s = "4543";
Console.WriteLine(makeEven(s));
}
}
// Function to make the string even by swapping the last digit with the nearest even
// digit
function makeEven(s) {
let n = s.length;
let even = Number.MAX_SAFE_INTEGER;
let index = -1;
// Iterating through the string to find an even digit
for (let i = 0; i < n - 1; i++) {
if ((s.charCodeAt(i) - '0'.charCodeAt(0)) % 2 === 0) {
even = s.charCodeAt(i) - '0'.charCodeAt(0);
index = i;
}
// Checking if the even digit found is smaller than the last digit
if (even <= (s.charCodeAt(n - 1) - '0'.charCodeAt(0)))
break;
}
// If no even digit is found, return the original string
if (even === Number.MAX_SAFE_INTEGER)
return s;
// Swapping the even digit with the last digit
let sArray = s.split('');
let temp = sArray[index];
sArray[index] = sArray[n - 1];
sArray[n - 1] = temp;
return sArray.join(''); // Return the modified string
}
let s = "4543";
console.log(makeEven(s));
Output
4534