VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-even-number-that-can-be-formed-by-any-number-of-swaps/

⇱ Largest even number that can be formed by any number of swaps - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest even number that can be formed by any number of swaps

Last Updated : 11 Jul, 2025

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.

Examples: 

Input: N = 1324 
Output: 4312

Input: N = 135 
Output: -1 
No even number can be formed using odd digits.

Recommended Practice

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 needed to be sorted can be at most 10 in the worst case.

Below is the implementation of the above approach: 


Output: 
4322210

 

Time Complexity: O(n + MAX)
Auxiliary Space: O(MAX)
 

Comment