Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Largest even number that can be formed by any number of swaps
Next article icon

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

Last Updated : 15 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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
Largest Even Number
Try It!

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: 

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; const int MAX = 10;  // Function to return the maximum // even number that can be formed // with any number of digit swaps string getMaxEven(string str, int len) {      // To store the frequencies of     // all the digits     int freq[MAX] = { 0 };      // To store the minimum even digit     // and the minimum overall digit     int i, minEvenDigit = MAX;     for (i = 0; i < len; i++) {         int digit = str[i] - '0';         freq[digit]++;          // If digit is even then update         // the minimum even digit         if (digit % 2 == 0)             minEvenDigit = min(digit, minEvenDigit);     }      // If there is no even digit then     // it is not possible to generate     // an even number with swaps     if (minEvenDigit == MAX)         return "-1";      // Decrease the frequency of the     // digits that need to be swapped     freq[minEvenDigit]--;      i = 0;     // Take every digit starting from the maximum     // in order to maximize the number     for (int j = MAX - 1; j >= 0; j--) {          // Take current digit number of times         // it appeared in the original number         for (int k = 0; k < freq[j]; k++)             str[i++] = (char)(j + '0');     }      // Append once instance of the minimum     // even digit in the end to make the number even     str[i] = (char)(minEvenDigit + '0');      return str; }  // Driver code int main() {     string str = "1023422";     int len = str.length();      // Function call     cout << getMaxEven(str, len);      return 0; } 
Java
// Java implementation of the approach import java.io.*; public class GFG {      static int MAX = 10;      // Function to return the maximum     // even number that can be formed     // with any number of digit swaps     static String getMaxEven(String str, int len)     {       //To store the max even number         String maxEven="";         // To store the frequencies of         // all the digits         int[] freq = new int[MAX];          // To store the minimum even digit         int i, minEvenDigit = MAX;         for (i = 0; i < len; i++) {             int digit = str.charAt(i) - '0';             freq[digit]++;              // If digit is even then update             // the minimum even digit             if (digit % 2 == 0)                 minEvenDigit                     = Math.min(digit, minEvenDigit);          }          // If there is no even digit then         // it is not possible to generate         // an even number with swaps         if (minEvenDigit == MAX)             return "-1";          // Decrease the frequency of the         // minEvenDigit         freq[minEvenDigit]--;                   i = MAX-1;          // Take every digit starting from the maximum         // in order to maximize the number        while(i>=0)        {            // Take current digit number of times             // it appeared in the original number            if(freq[i]>0)            {              maxEven= maxEven+i;              freq[i]--;            }else              i--;                      }          // Append the minimum even digit         // in the end to make the number even          maxEven= maxEven+minEvenDigit;          return maxEven;     }      // Driver code     public static void main(String[] args)     {         String str = "1023422";         int len = str.length();          // Function call         System.out.println(getMaxEven(str, len));     } } 
Python3
# Python3 implementation of the approach  MAX = 10  # Function to return the maximum # even number that can be formed # with any number of digit swaps   def getMaxEven(string, length):      string = list(string)      # To store the frequencies of     # all the digits     freq = [0]*MAX      # To store the minimum even digit     # and the minimum overall digit     minEvenDigit = MAX     minDigit = MAX     for i in range(length):         digit = ord(string[i]) - ord('0')         freq[digit] += 1          # If digit is even then update         # the minimum even digit         if (digit % 2 == 0):             minEvenDigit = min(digit, minEvenDigit)          # Update the overall minimum digit         minDigit = min(digit, minDigit)      # If there is no even digit then     # it is not possible to generate     # an even number with swaps     if (minEvenDigit == MAX):         return "-1"      # Decrease the frequency of the     # digits that need to be swapped     freq[minEvenDigit] -= 1     freq[minDigit] -= 1      i = 0      # Take every digit starting from the maximum     # in order to maximize the number     for j in range(MAX - 1, -1, -1):          # Take current digit number of times         # it appeared in the original number         for k in range(freq[j]):             string[i] = chr(j + ord('0'))             i += 1          # If current digit equals to the         # minimum even digit then one instance of it         # needs to be swapped with the minimum overall digit         # i.e. append the minimum digit here         if (j == minEvenDigit):             string[i] = chr(minDigit + ord('0'))             i += 1      # Append once instance of the minimum     # even digit in the end to make the number even     string[-1] = chr(minEvenDigit + ord('0'))      return "".join(string)   # Driver code if __name__ == "__main__":     string = "1023422"     length = len(string)      # Function call     print(getMaxEven(string, length))  # This code is contributed by AnkitRai01 
C#
// C# implementation of the approach using System;  class GFG {      static int MAX = 10;      // Function to return the maximum     // even number that can be formed     // with any number of digit swaps     static String getMaxEven(char[] str, int len)     {          // To store the frequencies of         // all the digits         int[] freq = new int[MAX];          // To store the minimum even digit         // and the minimum overall digit         int i, minEvenDigit = MAX, minDigit = MAX;         for (i = 0; i < len; i++) {             int digit = str[i] - '0';             freq[digit]++;              // If digit is even then update             // the minimum even digit             if (digit % 2 == 0)                 minEvenDigit                     = Math.Min(digit, minEvenDigit);              // Update the overall minimum digit             minDigit = Math.Min(digit, minDigit);         }          // If there is no even digit then         // it is not possible to generate         // an even number with swaps         if (minEvenDigit == MAX)             return "-1";          // Decrease the frequency of the         // digits that need to be swapped         freq[minEvenDigit]--;         freq[minDigit]--;          i = 0;          // Take every digit starting from the maximum         // in order to maximize the number         for (int j = MAX - 1; j >= 0; j--) {              // Take current digit number of times             // it appeared in the original number             for (int k = 0; k < freq[j]; k++)                 str[i++] = (char)(j + '0');              // If current digit equals to the             // minimum even digit then one instance of it             // needs to be swapped with the minimum overall             // digit i.e. append the minimum digit here             if (j == minEvenDigit)                 str[i++] = (char)(minDigit + '0');         }          // Append once instance of the minimum         // even digit in the end to make the number even         str[i - 1] = (char)(minEvenDigit + '0');          return String.Join("", str);     }      // Driver code     public static void Main(String[] args)     {         char[] str = "1023422".ToCharArray();         int len = str.Length;          // Function call         Console.WriteLine(getMaxEven(str, len));     } }  // This code has been contributed by 29AjayKumar 
JavaScript
<script>     // Javascript implementation of the approach          let MAX = 10;       // Function to return the maximum     // even number that can be formed     // with any number of digit swaps     function getMaxEven(str, len)     {           // To store the frequencies of         // all the digits         let freq = new Array(MAX);         freq.fill(0);           // To store the minimum even digit         // and the minimum overall digit         let i, minEvenDigit = MAX, minDigit = MAX;         for (i = 0; i < len; i++) {             let digit = str[i].charCodeAt() - '0'.charCodeAt();             freq[digit]++;               // If digit is even then update             // the minimum even digit             if (digit % 2 == 0)                 minEvenDigit                     = Math.min(digit, minEvenDigit);               // Update the overall minimum digit             minDigit = Math.min(digit, minDigit);         }           // If there is no even digit then         // it is not possible to generate         // an even number with swaps         if (minEvenDigit == MAX)             return "-1";           // Decrease the frequency of the         // digits that need to be swapped         freq[minEvenDigit]--;         freq[minDigit]--;           i = 0;           // Take every digit starting from the maximum         // in order to maximize the number         for (let j = MAX - 1; j >= 0; j--) {               // Take current digit number of times             // it appeared in the original number             for (let k = 0; k < freq[j]; k++)                 str[i++] = String.fromCharCode(j + '0'.charCodeAt());               // If current digit equals to the             // minimum even digit then one instance of it             // needs to be swapped with the minimum overall             // digit i.e. append the minimum digit here             if (j == minEvenDigit)                 str[i++] = String.fromCharCode(minDigit + '0'.charCodeAt());         }           // Append once instance of the minimum         // even digit in the end to make the number even         str[i - 1] = String.fromCharCode(minEvenDigit + '0'.charCodeAt());           return str.join("");     }          let str = "1023422".split('');     let len = str.length;      // Function call     document.write(getMaxEven(str, len));      </script> 

Output: 
4322210

 

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


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

M

md1844
Improve
Article Tags :
  • Strings
  • Sorting
  • Mathematical
  • DSA
  • frequency-counting
Practice Tags :
  • Mathematical
  • Sorting
  • Strings

Similar Reads

    Find maximum number that can be formed using digits of a given number
    Given a number, write a program to find a maximum number that can be formed using all of the digits of this number.Examples: Input : 38293367Output : 98763332Input : 1203465Output: 6543210Simple Approach: The simple method to solve this problem is to extract and store the digits of the given number
    6 min read
    Greatest number less than equal to B that can be formed from the digits of A
    Given two integers A and B, the task is to find the greatest number ? B that can be formed using all the digits of A.Examples: Input: A = 123, B = 222 Output: 213 123, 132 and 213 are the only valid numbers which are ? 222. 213 is the maximum among them.Input: A = 3921, B = 10000 Output: 9321 Approa
    8 min read
    Largest number with one swap allowed
    Given a numeric string s, return the lexicographically largest string possible by swapping at most one pair of characters.Note: Leading zeros are not allowed.Examples: Input: s = "768"Output: "867"Explanation: Swapping the 1st and 3rd characters(7 and 8 respectively), gives the lexicographically lar
    8 min read
    Maximum number formed from array with K number of adjacent swaps allowed
    Given an array a[ ] and the number of adjacent swap operations allowed are K. The task is to find the max number that can be formed using these swap operations.  Examples:  Input : a[]={ 1, 2, 9, 8, 1, 4, 9, 9, 9 }, K = 4 Output : 9 8 1 2 1 4 9 9 9 After 1st swap a[ ] becomes 1 9 2 8 1 4 9 9 9 After
    9 min read
    Largest number divisible by 90 that can be made using 0 and 5
    Given an array containing N elements. Each element is either 0 or 5. Find the largest number divisible by 90 that can be made using any number of elements of this array and arranging them in any way. Examples: Input : arr[] = {5, 5, 5, 5, 5, 5, 5, 5, 0, 5, 5}Output : 5555555550Input : arr[] = {5, 0}
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences