Minimum number of operations required to maximize the Binary String

• Difficulty Level : Medium
• Last Updated : 20 May, 2021

Given a binary string S, the task is to find the minimum number of swaps required to be performed to maximize the value represented by S.

Examples:

Input: S = “1010001”
Output:
Explanation: Swapping S and S, modifies the string to 1110000, thus, maximizing the number that can be generated from the string.
Input: S = “110001001”
Output:
Explanation: Swapping S with S and S with S, we get 111100000 which is the required string

Naive Approach:
It can be observed that, in order to maximize the required string, the characters should be swapped such that all 0s should be on the right and all the 1s are on the left. Therefore, the string needs to be modified to a “1…10…0” sequence.

Follow the below steps to solve the problem:

1. Count the number of 1s in the string S, say cnt1.
2. Count the number of 0s in substring S, …, S[cnt1-1], say cnt0.
3. Print cnt0 as the required answer.

Below is the implementation of above approach:

C++

 // C++ Program to implement// the above approach#include using namespace std; // Function to find the number// of operations requiredint minOperation(string s, int n){     // Count of 1's    int cnt1 = 0;    for (int i = 0; i < n; i++) {        if (s[i] == '1')            cnt1++;    }     // Count of 0's upto (cnt1)-th index    int cnt0 = 0;    for (int i = 0; i < cnt1; i++) {        if (s[i] == '0')            cnt0++;    }     // Return the answer    return cnt0;} // Driver Codeint main(){    int n = 8;     string s = "01001011";     int ans = minOperation(s, n);     cout << ans << endl;}

Java

 // Java program to implement// the above approachclass GFG{ // Function to find the number// of operations requiredstatic int minOperation(String s, int n){         // Count of 1's    int cnt1 = 0;    for(int i = 0; i < n; i++)    {        if (s.charAt(i) == '1')            cnt1++;    }     // Count of 0's upto (cnt1)-th index    int cnt0 = 0;    for(int i = 0; i < cnt1; i++)    {        if (s.charAt(i) == '0')            cnt0++;    }     // Return the answer    return cnt0;} // Driver Codepublic static void main(String[] args){    int n = 8;     String s = "01001011";     int ans = minOperation(s, n);     System.out.print(ans + "\n");}} // This code is contributed by PrinciRaj1992

Python3

 # Python3 program to implement# the above approach # Function to find the number# of operations requireddef minOperation(s, n):         # Count of 1's    cnt1 = 0;         for i in range(n):        if (ord(s[i]) == ord('1')):            cnt1 += 1;     # Count of 0's upto (cnt1)-th index    cnt0 = 0;         for i in range(0, cnt1):        if (s[i] == '0'):            cnt0 += 1;     # Return the answer    return cnt0; # Driver Codeif __name__ == '__main__':         n = 8;    s = "01001011";    ans = minOperation(s, n);     print(ans); # This code is contributed by Amit Katiyar

C#

 // C# program to implement// the above approachusing System; class GFG{ // Function to find the number// of operations requiredstatic int minOperation(String s, int n){         // Count of 1's    int cnt1 = 0;    for(int i = 0; i < n; i++)    {        if (s[i] == '1')            cnt1++;    }     // Count of 0's upto (cnt1)-th index    int cnt0 = 0;    for(int i = 0; i < cnt1; i++)    {        if (s[i] == '0')            cnt0++;    }     // Return the answer    return cnt0;} // Driver Codepublic static void Main(String[] args){    int n = 8;     String s = "01001011";     int ans = minOperation(s, n);     Console.Write(ans + "\n");}} // This code is contributed by PrinciRaj1992
Output:
3

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

Efficient Approach:

The above approach can be further optimized using Two Pointers technique. Follow the below steps to solve the problem:

• Set two pointers i = 0 and j = S.length() – 1 and iterate until i exceeds j.
• Increase count, if S[i] is equal to ‘0‘ and S[j] is equal to ‘1‘.
• Increment i if S[i] is ‘1‘ until a ‘0‘ appears. Similarly, decrease j until S[j] is equal to ‘1‘.
• Print count as the required answer.

Below is the implementation of above approach:

C++

 // C++ Program to implement// the above approach#include using namespace std; // Function to find the number// of operations requiredint minOperation(string s, int n){     int ans = 0;    int i = 0, j = n - 1;    while (i < j) {         // Swap 0's and 1's        if (s[i] == '0' && s[j] == '1') {            ans++;            i++;            j--;            continue;        }         if (s[i] == '1') {            i++;        }         if (s[j] == '0') {            j--;        }    }     // Return the answer    return ans;} // Driver Codeint main(){    int n = 8;     string s = "10100101";     int ans = minOperation(s, n);     cout << ans << endl;}

Java

 // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the number// of operations requiredstatic int minOperation(String s, int n){    int ans = 0;    int i = 0, j = n - 1;         while (i < j)    {                 // Swap 0's and 1's        if (s.charAt(i) == '0' &&            s.charAt(j) == '1')        {            ans++;            i++;            j--;            continue;        }         if (s.charAt(i) == '1')        {            i++;        }         if (s.charAt(j) == '0')        {            j--;        }    }     // Return the answer    return ans;} // Driver codepublic static void main (String[] args){    int n = 8;         String s = "10100101";         System.out.println(minOperation(s, n));}} // This code is contributed by offbeat

Python3

 # Python3 program to implement# the above approach # Function to find the number# of operations requireddef minOperation(s, n):    ans = 0;    i = 0; j = n - 1;     while (i < j):         # Swap 0's and 1's        if (s[i] == '0' and s[j] == '1'):            ans += 1;            i += 1;            j -= 1;            continue;                 if (s[i] == '1'):            i += 1;                 if (s[j] == '0'):            j -= 1;             # Return the answer    return ans; # Driver codeif __name__ == '__main__':    n = 8;     s = "10100101";     print(minOperation(s, n)); # This code is contributed by sapnasingh4991

C#

 // C# program to implement// the above approachusing System;class GFG{ // Function to find the number// of operations requiredstatic int minOperation(String s, int n){    int ans = 0;    int i = 0, j = n - 1;         while (i < j)    {                 // Swap 0's and 1's        if (s[i] == '0' &&            s[j] == '1')        {            ans++;            i++;            j--;            continue;        }         if (s[i] == '1')        {            i++;        }         if (s[j] == '0')        {            j--;        }    }     // Return the answer    return ans;} // Driver codepublic static void Main(String[] args){    int n = 8;         String s = "10100101";         Console.WriteLine(minOperation(s, n));}} // This code is contributed by sapnasingh4991

Javascript



Output:

2

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

My Personal Notes arrow_drop_up