Open In App

Minimize given Number by swapping adjacent digits with odd difference

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S of length N representing an integer that consists of only characters ‘1’, ‘2’ and ‘3’, the task is to find the smallest number that can be formed from the string by swapping the adjacent characters if their absolute difference is odd any number of times.

Examples:

Input: S = “213123”
Output: 122313
Explanation: The integer representing the output string (i.e. 122313) is smaller than the input string. 
The swapping done are as follows (characters to be swapped are in bold) :
213123 -> 123123
123123 -> 123213
123213 -> 122313

Input: S = “122333”
Output: 122333

 

Approach: This problem can be easily solved by using the greedy approach using the following observation:

1 and 3 cannot be swapped as their difference is 2 (which is even). 
1 and 2 can be swapped and so can be 2 and 3 as their difference is 1 (odd).

So keeping that in mind all the 2s can be placed at any position in the resultant string. The optimal position is to place all the 2s after the 1s which are situated at the starting of the string.

Follow the steps mentioned below to implement the observation:

  • Count all the 2s present in the string.
  • Keep the group of 1s unchanged if they are at the starting of the string i.e. keep them in the starting in the resultant string also.
  • Add all the 2s of the string after this group of 1s.
  • Finally, add the remaining occurrences of 1 and 3 into the resultant string in the same order as they were in given string (since 1 and 3 cannot be swapped).

Below is the implementation of the above approach.

C++




// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum number
// corresponding to the given string
// by swapping adjacent numbers if
// their difference is odd
string findMinimumString(string S)
{
    // Finding length of given string
    int N = S.length();
 
    // Declaring variable to store
    // the first occurrence of 3
    int pos = -1;
 
    // Declaring variables to store
    // the count of 1 before the first 3
    // and count of all 2 in given string
    int count1 = 0, count2 = 0;
 
    // Traversing the string and counting the
    // 1s before first occurrence of 3
    // and count of 2s in whole string
    for (int i = 0; i < N; i++) {
        if (pos == -1 && S[i] == '1')
            count1++;
        else if (pos == -1 && S[i] == '3')
            pos = i;
        else if (S[i] == '2')
            count2++;
    }
 
    // Declaring empty string to store answer
    string answer = "";
 
    // Adding all occurrences of 1
    // before first occurrence of 3
    // to the answer
    while (count1--)
        answer += '1';
 
    // Adding all the occurrences of 2
    // into the answer
    while (count2--)
        answer += '2';
 
    // Adding the rest of the occurrences
    // of 1 and 3 to the answer in same order
    // as that in given string
    if (pos != -1) {
        while (pos < N) {
            if (S[pos] != '2')
                answer += S[pos];
            pos++;
        }
    }
 
    // Returning answer string
    return answer;
}
 
// Driver Code
int main()
{
    string S = "213123";
    string minimum_string
        = findMinimumString(S);
    cout << minimum_string;
    return 0;
}


Java




// JAVA program for above approach
import java.util.*;
class GFG
{
   
    // Function to find minimum number
    // corresponding to the given string
    // by swapping adjacent numbers if
    // their difference is odd
    public static String findMinimumString(String S)
    {
       
        // Finding length of given string
        int N = S.length();
 
        // Declaring variable to store
        // the first occurrence of 3
        int pos = -1;
 
        // Declaring variables to store
        // the count of 1 before the first 3
        // and count of all 2 in given string
        int count1 = 0, count2 = 0;
 
        // Traversing the string and counting the
        // 1s before first occurrence of 3
        // and count of 2s in whole string
        for (int i = 0; i < N; i++) {
            if (pos == -1 && S.charAt(i) == '1')
                count1++;
            else if (pos == -1 && S.charAt(i) == '3')
                pos = i;
            else if (S.charAt(i) == '2')
                count2++;
        }
 
        // Declaring empty string to store answer
        String answer = "";
 
        // Adding all occurrences of 1
        // before first occurrence of 3
        // to the answer
        while ((count1--) != 0)
            answer += '1';
 
        // Adding all the occurrences of 2
        // into the answer
        while ((count2--) != 0)
            answer += '2';
 
        // Adding the rest of the occurrences
        // of 1 and 3 to the answer in same order
        // as that in given string
        if (pos != -1) {
            while (pos < N) {
                if (S.charAt(pos) != '2')
                    answer += S.charAt(pos);
                pos++;
            }
        }
 
        // Returning answer string
        return answer;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String S = "213123";
        String minimum_string = findMinimumString(S);
        System.out.print(minimum_string);
    }
}
 
// This code is contributed by Taranpreet


Python3




# Function to find minimum number
# corresponding to the given string
# by swapping adjacent numbers if
# their difference is odd
def findMinimumString(S) :
     
    # Finding length of given string
    N = len(S)
 
    # Declaring variable to store
    # the first occurrence of 3
    pos = -1
 
    # Declaring variables to store
    # the count of 1 before the first 3
    # and count of all 2 in given string
    count1 = 0
    count2 = 0
 
    # Traversing the string and counting the
    # 1s before first occurrence of 3
    # and count of 2s in whole string
    for i in range(N) :
        if (pos == -1 and S[i] == '1'):
            count1 += 1
        elif (pos == -1 and S[i] == '3'):
            pos = i
        elif (S[i] == '2') :
            count2 += 1
 
    # Declaring empty string to store answer
    answer = ""
 
    # Adding all occurrences of 1
    # before first occurrence of 3
    # to the answer
    while (count1) :
        answer += '1'
        count1 -= 1
 
    # Adding all the occurrences of 2
    # into the answer
    while (count2):
        answer += '2'
        count2 -= 1
 
    # Adding the rest of the occurrences
    # of 1 and 3 to the answer in same order
    # as that in given string
    if (pos != -1) :
        while (pos < N) :
            if (S[pos] != '2'):
                answer += S[pos]
            pos += 1
         
    # Returning answer string
    return answer
 
# Driver Code
S = "213123"
minimum_string = findMinimumString(S)
print(minimum_string)
 
# This code is contributed by sanjoy_62.


C#




// C# program for above approach
using System;
class GFG
{
 
  // Function to find minimum number
  // corresponding to the given string
  // by swapping adjacent numbers if
  // their difference is odd
  static String findMinimumString(string S)
  {
 
    // Finding length of given string
    int N = S.Length;
 
    // Declaring variable to store
    // the first occurrence of 3
    int pos = -1;
 
    // Declaring variables to store
    // the count of 1 before the first 3
    // and count of all 2 in given string
    int count1 = 0, count2 = 0;
 
    // Traversing the string and counting the
    // 1s before first occurrence of 3
    // and count of 2s in whole string
    for (int i = 0; i < N; i++) {
      if (pos == -1 && S[i] == '1')
        count1++;
      else if (pos == -1 && S[i] == '3')
        pos = i;
      else if (S[i] == '2')
        count2++;
    }
 
    // Declaring empty string to store answer
    string answer = "";
 
    // Adding all occurrences of 1
    // before first occurrence of 3
    // to the answer
    while ((count1--) != 0)
      answer += '1';
 
    // Adding all the occurrences of 2
    // into the answer
    while ((count2--) != 0)
      answer += '2';
 
    // Adding the rest of the occurrences
    // of 1 and 3 to the answer in same order
    // as that in given string
    if (pos != -1) {
      while (pos < N) {
        if (S[pos] != '2')
          answer += S[pos];
        pos++;
      }
    }
 
    // Returning answer string
    return answer;
  }
 
  // Driver Code
  public static void Main()
  {
    string S = "213123";
    string minimum_string = findMinimumString(S);
    Console.Write(minimum_string);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
    // JavaScript program for above approach
 
    // Function to find minimum number
    // corresponding to the given string
    // by swapping adjacent numbers if
    // their difference is odd
    const findMinimumString = (S) => {
     
        // Finding length of given string
        let N = S.length;
 
        // Declaring variable to store
        // the first occurrence of 3
        let pos = -1;
 
        // Declaring variables to store
        // the count of 1 before the first 3
        // and count of all 2 in given string
        let count1 = 0, count2 = 0;
 
        // Traversing the string and counting the
        // 1s before first occurrence of 3
        // and count of 2s in whole string
        for (let i = 0; i < N; i++) {
            if (pos == -1 && S[i] == '1')
                count1++;
            else if (pos == -1 && S[i] == '3')
                pos = i;
            else if (S[i] == '2')
                count2++;
        }
 
        // Declaring empty string to store answer
        let answer = "";
 
        // Adding all occurrences of 1
        // before first occurrence of 3
        // to the answer
        while (count1--)
            answer += '1';
 
        // Adding all the occurrences of 2
        // into the answer
        while (count2--)
            answer += '2';
 
        // Adding the rest of the occurrences
        // of 1 and 3 to the answer in same order
        // as that in given string
        if (pos != -1) {
            while (pos < N) {
                if (S[pos] != '2')
                    answer += S[pos];
                pos++;
            }
        }
 
        // Returning answer string
        return answer;
    }
 
    // Driver Code
 
    let S = "213123";
    let minimum_string
        = findMinimumString(S);
    document.write(minimum_string);
 
// This code is contributed by rakeshsahni
 
</script>


 
 

Output

122313

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 



Last Updated : 25 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads