Minimum integer that can be obtained by swapping adjacent digits of different parity

Given an integer N, the task is to find the minimum integer that can be obtained from the given integer such that the adjacent digits of different parity can be swapped any no of times.Â
Two digits of different parity means that they will have different remainders when divided by two.
Examples:Â
Â
Input: N = 64432Â
Output: 36442Â
Explanation:Â
Swap the 4th and 3rd digit; N = 64342Â
Swap the 3rd and 2nd digit; N = 63442Â
Swap the 2nd and 1st digit; N = 36442
Input :Â
3137Â
Output :Â
3137Â
Â
Â
Approach: The idea of the approach is to use two stacks to keep the digits of the number.Â
Â
- In one stack, numbers which are divisible by two can be stored.
- In another stack, numbers which are not divisible by two can be stored.
- The elements are then pushed into both the stacks from reverse order of the number.
- Now, the element from the stack whose top contains the smaller element is popped and concatenated with the answer till one of the stacks is empty.
- The remaining elements of the stack are then concatenated which is not empty with the answer and finally the output is returned.
Below is the implementation of the above approach.
Â
CPP
// C++ implementation of the above approach.#include <bits/stdc++.h>using namespace std;// Function to return the minimum numberint minimumNo(int n){Â Â Â Â int ans = 0;Â Â Â Â stack<int> stack1;Â Â Â Â stack<int> stack2;Â Â Â Â while (n != 0) {Â Â Â Â Â Â Â Â int r = n % 10;Â
        // Store the elements which are        // divisible by two in stack1        if (r % 2 == 0) {            stack1.push(r);        }Â
        // Store the elements which are        // not divisible by two in stack2.        else {            stack2.push(r);        }        n = n / 10;    }Â
    while (!stack1.empty() && !stack2.empty()) {Â
        // Concatenate the answer with smaller value        // of the topmost elements of both the        // stacks and then pop that element        if (stack1.top() < stack2.top()) {            ans = ans * 10 + stack1.top();            stack1.pop();        }        else {            ans = ans * 10 + stack2.top();            stack2.pop();        }    }Â
    // Concatenate the answer with remaining     // values of stack1.    while (!stack1.empty()) {        ans = ans * 10 + stack1.top();        stack1.pop();    }Â
    // Concatenate the answer with remaining     // values of stack2.    while (!stack2.empty()) {        ans = ans * 10 + stack2.top();        stack2.pop();    }    return ans;}Â
// Driver codeint main(){Â Â Â Â int n1 = 64432;Â
    // Function calling    cout << minimumNo(n1) << endl;Â
    int n2 = 3137;    cout << minimumNo(n2) << endl;Â
    return 0;} |
Java
// Java implementation of the above approach.import java.util.*;Â
class GFG{Â Â Â Â Â // Function to return the minimum numberstatic int minimumNo(int n){Â Â Â Â int ans = 0;Â Â Â Â Stack<Integer> stack1 = new Stack<Integer>();Â Â Â Â Stack<Integer> stack2 = new Stack<Integer>();Â Â Â Â while (n != 0)Â Â Â Â {Â Â Â Â Â Â Â Â int r = n % 10;Â
        // Store the elements which are        // divisible by two in stack1        if (r % 2 == 0)        {            stack1.add(r);        }Â
        // Store the elements which are        // not divisible by two in stack2.        else        {            stack2.add(r);        }        n = n / 10;    }Â
    while (!stack1.isEmpty() && !stack2.isEmpty())    {Â
        // Concatenate the answer with smaller value        // of the topmost elements of both the        // stacks and then pop that element        if (stack1.peek() < stack2.peek())        {            ans = ans * 10 + stack1.peek();            stack1.pop();        }        else        {            ans = ans * 10 + stack2.peek();            stack2.pop();        }    }Â
    // Concatenate the answer with remaining     // values of stack1.    while (!stack1.isEmpty())    {        ans = ans * 10 + stack1.peek();        stack1.pop();    }Â
    // Concatenate the answer with remaining     // values of stack2.    while (!stack2.isEmpty())    {        ans = ans * 10 + stack2.peek();        stack2.pop();    }    return ans;}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int n1 = 64432;Â
    // Function calling    System.out.print(minimumNo(n1) + "\n");Â
    int n2 = 3137;    System.out.print(minimumNo(n2) + "\n");}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 implementation of the above approach.Â
# Function to return the minimum numberdef minimumNo(n):Â Â Â Â ans = 0Â Â Â Â stack1 = []Â Â Â Â stack2 = []Â Â Â Â while (n != 0):Â Â Â Â Â Â Â Â r = n % 10Â
        # Store the elements which are        # divisible by two in stack1        if (r % 2 == 0):            stack1.append(r)Â
        # Store the elements which are        # not divisible by two in stack2.        else :            stack2.append(r)Â
        n = n // 10    while (len(stack1) > 0 and len(stack2) > 0):Â
        # Concatenate the answer with smaller value        # of the topmost elements of both the        # stacks and then pop that element        if (stack1[-1] < stack2[-1]):            ans = ans * 10 + stack1[-1]            del stack1[-1]Â
        else:            ans = ans * 10 + stack2[-1]            del stack2[-1]Â
    # Concatenate the answer with remaining    # values of stack1.    while (len(stack1) > 0):        ans = ans * 10 + stack1[-1]        del stack1[-1]Â
    # Concatenate the answer with remaining    # values of stack2.    while (len(stack2) > 0):        ans = ans * 10 + stack2[-1]        del stack2[-1]Â
    return ansÂ
# Driver coden1 = 64432Â
# Function callingprint(minimumNo(n1))Â
n2 = 3137print(minimumNo(n2))Â
# This code is contributed by mohit kumar 29 |
C#
// C# implementation of the above approach.using System;using System.Collections.Generic;Â
class GFG{Â Â Â Â Â // Function to return the minimum numberstatic int minimumNo(int n){Â Â Â Â int ans = 0;Â Â Â Â Stack<int> stack1 = new Stack<int>();Â Â Â Â Stack<int> stack2 = new Stack<int>();Â Â Â Â while (n != 0)Â Â Â Â {Â Â Â Â Â Â Â Â int r = n % 10;Â
        // Store the elements which are        // divisible by two in stack1        if (r % 2 == 0)        {            stack1.Push(r);        }Â
        // Store the elements which are        // not divisible by two in stack2.        else        {            stack2.Push(r);        }        n = n / 10;    }Â
    while (stack1.Count != 0 && stack2.Count != 0)    {Â
        // Concatenate the answer with smaller value        // of the topmost elements of both the        // stacks and then pop that element        if (stack1.Peek() < stack2.Peek())        {            ans = ans * 10 + stack1.Peek();            stack1.Pop();        }        else        {            ans = ans * 10 + stack2.Peek();            stack2.Pop();        }    }Â
    // Concatenate the answer with remaining     // values of stack1.    while (stack1.Count != 0)    {        ans = ans * 10 + stack1.Peek();        stack1.Pop();    }Â
    // Concatenate the answer with remaining     // values of stack2.    while (stack2.Count != 0)    {        ans = ans * 10 + stack2.Peek();        stack2.Pop();    }    return ans;}Â
// Driver codepublic static void Main(String[] args){Â Â Â Â int n1 = 64432;Â
    // Function calling    Console.Write(minimumNo(n1) + "\n");Â
    int n2 = 3137;    Console.Write(minimumNo(n2) + "\n");}}Â
// This code is contributed by PrinciRaj1992 |
Javascript
<script>Â
      // JavaScript implementation       // of the above approach.             // Function to return the minimum number      function minimumNo(n) {        var ans = 0;        var stack1 = [];        var stack2 = [];        while (n !== 0) {          var r = n % 10;Â
          // Store the elements which are          // divisible by two in stack1          if (r % 2 === 0) {            stack1.push(r);          }Â
          // Store the elements which are          // not divisible by two in stack2.          else {            stack2.push(r);          }          n = parseInt(n / 10);        }Â
        while (stack1.length !== 0 && stack2.length !== 0)        {          // Concatenate the answer with smaller value          // of the topmost elements of both the          // stacks and then pop that element          if (stack1[stack1.length - 1] <           stack2[stack2.length - 1]) {            ans = ans * 10 + stack1[stack1.length - 1];            stack1.pop();          } else {            ans = ans * 10 + stack2[stack2.length - 1];            stack2.pop();          }        }Â
        // Concatenate the answer with remaining        // values of stack1.        while (stack1.length !== 0) {          ans = ans * 10 + stack1[stack1.length - 1];          stack1.pop();        }Â
        // Concatenate the answer with remaining        // values of stack2.        while (stack2.length !== 0) {          ans = ans * 10 + stack2[stack2.length - 1];          stack2.pop();        }        return ans;      }Â
      // Driver code      var n1 = 64432;Â
      // Function calling      document.write(minimumNo(n1) + "<br>");Â
      var n2 = 3137;      document.write(minimumNo(n2) + "<br>");       </script> |
Output:Â
36442 3137
Â
Time Complexity: O(logN)
Auxiliary Space: O(logN).Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



