Find the maximum number formed by swapping digits of same parity

Given a number N, the task is to maximize this number by following the given conditions:
- The odd digit of the number can only be swapped by any odd digit present in the given number.
- The even digit of the number can only be swapped by any even digit present in the given number.
Examples:
Input: N = 234
Output: 432
Explanation: The 0th index is swapped with 2nd index.Input: N = 6587
Output: 8765
Explanation: The 0th index is swapped with 2nd index.
The 1st index is swapped with 3rd index.
Naive approach: If a digit in the given number N is even then find the greatest element to its right which is also even and finally swap both. similarly do the same, if the digit is odd.
Follow the steps mentioned below to implement the idea:
- Convert the given number N into string s (This will make traversing on each digit of the number easy)
- Iterate the string from 0 to s.length()-1:
- Use variables to store the maximum value to the right of current index (say maxi) and its position (say idx).
- Iterate the string from j = i+1 to s.length()-1
- If both ith digit and jth digit is of the same parity and jth digit is greater than ith, then update the maxi and idx.
- Otherwise, continue the iteration.
- Finally swap s[i] with s[idx]
- Return the integer value of the string s.
Below is the implementation of the above approach.
C++
// C++ code to implement the approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to maximize the numberint maximizedNumber(int num){    // String will be used to represent the    // number in string    string s = to_string(num);Â
    // Traversing the string    for (int i = 0; i < s.length(); i++) {        int maxi = s[i] - '0';        int idx = i;Â
        // Check ith digit with all        // the remaining unoperated        // string to maximize the string        for (int j = i + 1; j < s.length();             j++) {Â
            // If both the ith and            // jth digit is odd            if (maxi % 2 == 0                && (s[j] - '0') % 2 == 0) {Â
                // If the jth digit is                // greater than the ith digit                if (s[j] - '0' > maxi) {                    maxi = s[j] - '0';                    idx = j;                }            }Â
            // If both ith and            // jth digit is even            else if (maxi % 2 == 1                     && (s[j] - '0') % 2 == 1) {Â
                // If the jth digit is                // greater than ith digit.                if (s[j] - '0' > maxi) {                    maxi = s[j] - '0';                    idx = j;                }            }        }Â
        // Swap the largest digit to the right        // of ith digit with ith digit        swap(s[i], s[idx]);    }Â
    // Convert string into integer    return stoi(s);}Â
// Driver codeint main(){Â Â Â Â int N = 6587;Â
    // Function call    cout << maximizedNumber(N);    return 0;} |
Java
// Java code to implement the approachimport java.io.*;import java.util.*;Â
class GFG {Â Â static String swap(String str, int i, int j)Â Â {Â Â Â Â StringBuilder sb = new StringBuilder(str);Â Â Â Â sb.setCharAt(i, str.charAt(j));Â Â Â Â sb.setCharAt(j, str.charAt(i));Â Â Â Â return sb.toString();Â Â }Â
  // Function to maximize the number  public static int maximizedNumber(int num)  {    // String will be used to represent the    // number in string    String s = Integer.toString(num);Â
    // Traversing the string    for (int i = 0; i < s.length(); i++) {      int maxi = s.charAt(i) - '0';      int idx = i;Â
      // Check ith digit with all      // the remaining unoperated      // string to maximize the string      for (int j = i + 1; j < s.length(); j++) {Â
        // If both the ith and        // jth digit is odd        if (maxi % 2 == 0            && (s.charAt(j) - '0') % 2 == 0) {Â
          // If the jth digit is          // greater than the ith digit          if (s.charAt(j) - '0' > maxi) {            maxi = s.charAt(j) - '0';            idx = j;          }        }Â
        // If both ith and        // jth digit is even        else if (maxi % 2 == 1                 && (s.charAt(j) - '0') % 2 == 1) {Â
          // If the jth digit is          // greater than ith digit.          if (s.charAt(j) - '0' > maxi) {            maxi = s.charAt(j) - '0';            idx = j;          }        }      }Â
      // Swap the largest digit to the right      // of ith digit with ith digit      s = swap(s, i, idx);    }Â
    // Convert string into integer    return Integer.parseInt(s);  }Â
  public static void main(String[] args)  {    int N = 6587;Â
    // Function call    System.out.print(maximizedNumber(N));  }}Â
// This code is contributed by Rohit Pradhan |
Python3
# Python code to implement the approachÂ
# Function to maximize the numberdef maximizedNumber(num):Â
    # Array String will be used to represent the    # number in string    s = list(str(num))Â
    # Traversing the string    for i in range(len(s)):        maxi = int(s[i])        idx = iÂ
        # Check ith digit with all        # the remaining unoperated        # string to maximize the string        for j in range(i + 1,len(s)):Â
            # If both the ith and            # jth digit is odd            if ((maxi % 2 == 0) and (int(s[j]) % 2 == 0)):Â
                # If the jth digit is                # greater than the ith digit                if (int(s[j]) > maxi):                    maxi = int(s[j])                    idx = jÂ
            # If both ith and            # jth digit is even            elif ((maxi % 2 == 1) and (int(s[j]) % 2 == 1)):Â
                # If the jth digit is                # greater than ith digit.                if (int(s[j]) > maxi):                    maxi = int(s[j])                    idx = jÂ
        # Swap the largest digit to the right        # of ith digit with ith digit        s[i],s[idx] = s[idx],s[i]Â
    # Convert string into integer    return ''.join(s)Â
# Driver codeN = 6587Â
# Function callprint(maximizedNumber(N))Â
# This code is contributed by shinjanpatra |
C#
// C# code to implement the approachusing System;Â
public class GFG {     // Function to maximize the number  public static int maximizedNumber(int num)  {         // String will be used to represent the    // number in string    string s = num.ToString();Â
    // Traversing the string    for (int i = 0; i < s.Length; i++) {      int maxi = s[i] - '0';      int idx = i;Â
      // Check ith digit with all      // the remaining unoperated      // string to maximize the string      for (int j = i + 1; j < s.Length; j++) {Â
        // If both the ith and        // jth digit is odd        if (maxi % 2 == 0            && (s[j] - '0') % 2 == 0) {Â
          // If the jth digit is          // greater than the ith digit          if (s[j] - '0' > maxi) {            maxi = s[j] - '0';            idx = j;          }        }Â
        // If both ith and        // jth digit is even        else if (maxi % 2 == 1                 && (s[j] - '0') % 2 == 1) {Â
          // If the jth digit is          // greater than ith digit.          if (s[j] - '0' > maxi) {            maxi = s[j] - '0';            idx = j;          }        }      }Â
      // Swap the largest digit to the right      // of ith digit with ith digit      string swap = s.Substring(i, 1);      s = s.Remove(i, 1).Insert(i,                                s.Substring(idx, 1));      s = s.Remove(idx, 1).Insert(idx, swap);    }Â
    // Convert string into integer    return Int32.Parse(s);  }  public static void Main(string[] args)  {    int N = 6587;Â
    // Function call    Console.WriteLine(maximizedNumber(N));  }}Â
// This code is contributed by phasing17 |
Javascript
<script>// JavaScript code to implement the approachÂ
// Function to maximize the numberfunction maximizedNumber(num){    // Array String will be used to represent the    // number in string    var s = num.toString().split('');Â
    // Traversing the string    for (var i = 0; i < s.length; i++) {        var maxi = parseInt(s[i]);        var idx = i;Â
        // Check ith digit with all        // the remaining unoperated        // string to maximize the string        for (var j = i + 1; j < s.length;             j++) {Â
            // If both the ith and            // jth digit is odd            if ((maxi % 2 == 0)                && (parseInt(s[j]) % 2 == 0)) {Â
                // If the jth digit is                // greater than the ith digit                if (parseInt(s[j]) > maxi) {                    maxi = parseInt(s[j]);                    idx = j;                }            }Â
            // If both ith and            // jth digit is even            else if ((maxi % 2 == 1)                     && (parseInt(s[j])) % 2 == 1) {Â
                // If the jth digit is                // greater than ith digit.                if (parseInt(s[j]) > maxi) {                    maxi = parseInt(s[j]);                    idx = j;                }            }        }Â
        // Swap the largest digit to the right        // of ith digit with ith digit        var temp = s[i];        s[i] = s[idx];        s[idx] = temp;    }Â
    // Convert string into integer    return (s.join(''));}Â
// Driver codevar N = 6587;Â
// Function calldocument.write(maximizedNumber(N));Â
// This code is contributed by phasing17</script> |
8765
Time Complexity: O(N2), Where N is the length of the given string.
Auxiliary Space: O(N)
Efficient approach: This problem can be solved efficiently based on the following idea:
Store all even digits in non-increasing order and do the same for odd digits.Â
Now replace all stored even digits of given number in non-increasing order with even digits in it and do the same for odd digits.
Follow the steps mentioned below to implement the idea.
- Convert given number N into string s.
- Iterate over s and do the following:
- Store all even digits in a string (say evenDigit) and all odd digits in another string (say oddDigit).
- Sort both the strings in non-increasing order.
- Iterate over s and do the following:
- Use two iterators (say itr1 and itr2) to point to the next even or odd digit to be picked.
- If the digit in s is even, then replace it with the digit in evenDigit[itr1] and increment itr1.Â
- If the digit in s is odd, then replace it with the digit in oddDigit[itr2] and increment itr2.
- Finally, convert the string s into an integer and return it.
Below is the implementation of the above approach.
C++
// C++ code to implement the approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to maximize the numberint maximizedNumber(int num){    // Store all even digits    string oddDigit = "";Â
    // Store all odd digits    string evenDigit = "";Â
    // Convert given number into string    string s = to_string(num);Â
    for (int i = 0; i < s.size(); i++) {        // Check if digit is even or odd        if ((s[i] - '0') % 2 == 0) {            evenDigit += s[i];        }        else {            oddDigit += s[i];        }    }Â
    // Sort oddDigit and evenDigit string    // in non-increasing order.    sort(oddDigit.begin(), oddDigit.end(),         greater<int>());    sort(evenDigit.begin(), evenDigit.end(),         greater<int>());Â
    int i1 = 0, j1 = 0;Â
    for (int i = 0; i < s.size(); i++) {Â
        // If the current digit is even        // then replace it with evenDigit[i1]        if ((s[i] - '0') % 2 == 0) {            s[i] = evenDigit[i1];            i1++;        }Â
        // If the current digit is odd then        // replace it with the oddDigit[j1]        else {            s[i] = oddDigit[j1];            j1++;        }    }Â
    return stoi(s);}Â
// Driver codeint main(){Â Â Â Â int N = 6587;Â
    // Function call    cout << maximizedNumber(N);    return 0;} |
Java
// Java code to implement the approachimport java.util.*;Â
// Helper class implementing Comparator interface// to compare characters of a string in non// increasing orderclass charSort implements Comparator<Character> {Â
  @Override public int compare(Character c1, Character c2)  {    // Ignoring case    return Character.compare(Character.toLowerCase(c2),                             Character.toLowerCase(c1));  }};Â
class GFG {Â
  // Function to maximize the number  static int maximizedNumber(int num)  {    // Store all even digits    ArrayList<Character> oddDigit      = new ArrayList<Character>();Â
    // Store all odd digits    ArrayList<Character> evenDigit      = new ArrayList<Character>();Â
    // Convert given number into char array    char[] s = (String.valueOf(num)).toCharArray();Â
    for (int i = 0; i < s.length; i++) {      // Check if digit is even or odd      if ((s[i] - '0') % 2 == 0) {        evenDigit.add(s[i]);      }      else {        oddDigit.add(s[i]);      }    }Â
    // Sort oddDigit and evenDigit string    // in non-increasing order.    oddDigit.sort(new charSort());    evenDigit.sort(new charSort());Â
    int i1 = 0, j1 = 0;Â
    for (int i = 0; i < s.length; i++) {Â
      // If the current digit is even      // then replace it with evenDigit[i1]      if ((s[i] - '0') % 2 == 0) {        s[i] = evenDigit.get(i1);        i1++;      }Â
      // If the current digit is odd then      // replace it with the oddDigit[j1]      else {        s[i] = oddDigit.get(j1);        j1++;      }    }Â
    return Integer.parseInt(new String(s));  }Â
  // Driver Code  public static void main(String[] args)  {    int N = 6587;Â
    // Function call    System.out.println(maximizedNumber(N));  }}Â
// This code is contributed by phasing17 |
Python3
# Python3 code to implement the approachÂ
# Function to maximize the numberdef maximizedNumber(num):Â
    # Store all even digits    oddDigit = "";Â
    # Store all odd digits    evenDigit = "";Â
    # Convert given number into string    s = list(str(num))Â
    for i in range(len(s)):        # Check if digit is even or odd        if (int(s[i]) % 2 == 0):            evenDigit += s[i];                 else:            oddDigit += s[i];         oddDigit = list(oddDigit)    evenDigit = list(evenDigit)         # Sort oddDigit and evenDigit string    # in non-increasing order.    oddDigit.sort();    oddDigit.reverse();    evenDigit.sort();    evenDigit.reverse();Â
    i1 = 0;    j1 = 0;Â
    for i in range(len(s)):Â
        # If the current digit is even        # then replace it with evenDigit[i1]        if (int(s[i]) % 2 == 0):            s[i] = evenDigit[i1];            i1 += 1         Â
        # If the current digit is odd then        # replace it with the oddDigit[j1]        else :            s[i] = oddDigit[j1];            j1 += 1Â
    return "".join(s)Â
# Driver codeN = 6587;Â
#Function callprint(maximizedNumber(N));Â
# This code is contributed by phasing17 |
C#
// C# code to implement the approachusing System;using System.Collections.Generic;Â
// Helper class implementing Comparator interface// to compare characters of a string in non// increasing orderclass charSort : Comparer<char> {Â
  public override int Compare(char c1, char c2)  {    // Ignoring case    return (Char.ToLower(c2))      .CompareTo(Char.ToLower(c1));  }};Â
Â
class GFG {Â
  // Function to maximize the number  static int maximizedNumber(int num)  {    // Store all even digits    List<char> oddDigit = new List<char>();Â
    // Store all odd digits    List<char> evenDigit = new List<char>();Â
    // Convert given number into char array    char[] s = (num.ToString()).ToCharArray();Â
    for (int i = 0; i < s.Length; i++) {      // Check if digit is even or odd      if ((s[i] - '0') % 2 == 0) {        evenDigit.Add(s[i]);      }      else {        oddDigit.Add(s[i]);      }    }Â
    // Sort oddDigit and evenDigit string    // in non-increasing order.    oddDigit.Sort(new charSort());    evenDigit.Sort(new charSort());Â
    int i1 = 0, j1 = 0;Â
    for (int i = 0; i < s.Length; i++) {Â
      // If the current digit is even      // then replace it with evenDigit[i1]      if ((s[i] - '0') % 2 == 0) {        s[i] = evenDigit[i1];        i1++;      }Â
      // If the current digit is odd then      // replace it with the oddDigit[j1]      else {        s[i] = oddDigit[j1];        j1++;      }    }Â
    return int.Parse(s);  }Â
  // Driver Code  public static void Main(string[] args)  {    int N = 6587;Â
    // Function call    Console.WriteLine(maximizedNumber(N));  }}Â
// This code is contributed by phasing17 |
Javascript
<script>// JavaScript code to implement the approachÂ
// Function to maximize the numberfunction maximizedNumber(num){    // Store all even digits    var oddDigit = "";Â
    // Store all odd digits    var evenDigit = "";Â
    // Convert given number into string    var s = num.toString().split("");Â
    for (var i = 0; i < s.length; i++) {        // Check if digit is even or odd        if (parseInt(s[i]) % 2 == 0) {            evenDigit += s[i];        }        else {            oddDigit += s[i];        }    }         oddDigit = oddDigit.split("");    evenDigit = evenDigit.split("");         // Sort oddDigit and evenDigit string    // in non-increasing order.    oddDigit.sort();    oddDigit.reverse();    evenDigit.sort();    evenDigit.reverse();Â
    var i1 = 0;    var j1 = 0;Â
    for (var i = 0; i < s.length; i++) {Â
        // If the current digit is even        // then replace it with evenDigit[i1]        if (parseInt(s[i]) % 2 == 0) {            s[i] = evenDigit[i1];            i1++;        }Â
        // If the current digit is odd then        // replace it with the oddDigit[j1]        else {            s[i] = oddDigit[j1];            j1++;        }    }Â
    return s.join("");}Â
// Driver codevar N = 6587;Â
// Function calldocument.write(maximizedNumber(N));Â
// This code is contributed by phasing17</script> |
8765
Time Complexity: O(M * log M), Where M is the number of digits present in N.
Auxiliary Space: O(M)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



