Given an integer N in the form of string, the task is to find the largest even number from the given number when you are allowed to do any number of swaps (swapping the digits of the number). If no even number can be formed then print -1.
Input: N = 1324
Input: N = 135
No even number can be formed using odd digits.
Approach: Sort the string in descending order then we will get the largest number possible with the given digit but it may or may not be an even number. In order to make it even (if it not already), an even digit from the number must be swapped with the last digit and in order to maximize the even number the even digit which is to be swapped must the smallest even digit from the number.
Note that the sorting can be done in linear time using frequency array for the digits of the number as the number of distinct elements that are need to be sorted can be at most 10 in the worst case.
Below is the implementation of the above approach:
Time Complexity: O(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Form the largest palindromic number using atmost two swaps
- Find the largest number that can be formed with the given digits
- Find the largest number that can be formed by changing at most K digits
- Largest number in given Array formed by repeatedly combining two same elements
- Find the Largest Cube formed by Deleting minimum Digits from a number
- Maximize number of groups formed with size not smaller than its largest element
- Minimum number of swaps required to sort an array of first N number
- Minimum number of swaps required to make a number divisible by 60
- Find smallest number formed by inverting digits of given number N
- Find maximum number that can be formed using digits of a given number
- Find the largest number smaller than integer N with maximum number of set bits
- Largest number dividing maximum number of elements in the array
- Number of times the largest perfect square number can be subtracted from N
- Find the largest good number in the divisors of given number N
- Lexicographical smallest number after at most K consecutive swaps
- Number of swaps to sort when only adjacent swapping allowed
- Minimum number of swaps required to sort an array
- Largest number less than N whose each digit is prime number
- Largest even number possible by using one swap operation in given number
- Minimum number of swaps required to make the string K periodic
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.