Min Number of Flips | Practice | GeeksforGeeks

Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped.
Example 1:
Input:
S = "001"
Output: 1
Explanation: 
We can flip the 0th bit to 1 to have
101.



Example 2:
Input:
S = "0001010111" 
Output: 2
Explanation: We can flip the 1st and 8th bit 
bit to have "0101010101"
101.


Your Task:
You don't need to read input or print anything. Your task is to complete the function minFlips() which takes the string S as input and returns the minimum number of flips required.

Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).

Constraints:
1<=|S|<=105
 
0
aditilal01in 6 hours
We first create two strings of the same size and compare it with the input to get the minimumint minFlips (string S){    string prod1="";    string prod2="";    for(int i=0;i<S.size();i++)    {        if(i%2 == 0)        {            prod1+="0";        }        else        {            prod1+="1";        }    }        for(int i=0;i<S.size();i++)    {        if(i%2 == 0)        {            prod2+="1";        }        else        {            prod2+="0";        }    }        int count1=0;    int count2=0;        for(int i=0;i<S.size();i++)    {        if(S[i]!=prod1[i])        {            count1++;        }    }    for(int i=0;i<S.size();i++)    {        if(S[i]!=prod2[i])        {            count2++;        }    }    int ans = min(count1,count2);    return ans;}
0
ayushmishra29
This comment was deleted.
0
shilsoumyadip2 weeks ago
int minFlips (string S){   // your code here   int c1 = 0;   int c2 = 0;   for(int i =0; i<S.length();i++)   {       if(i%2 != 0 and S[i] == '0') c1++;       if(i%2 == 0 and S[i] == '1') c1++;       if(i%2 != 0 and S[i] == '1') c2++;       if(i%2 == 0 and S[i] == '0') c2++;   }   return min(c1,c2);}
0
codewithaddy2 weeks ago
C++ Solution
Total Time Taken: 0.04/1.26
int minFlips (string s)
{
    
    int n=s.length();
    int c1=0,c2=0;
    for(int i=0; i<n;i++){
        if((s[i]-48)!=i%2){
            c1++;
        }
    }
    for(int i=0; i<n;i++){
        if((s[i]-48)==i%2){
            c2++;
        }
    }
    return min(c1,c2);
}
0
18951a04c33 weeks ago
Python 3
class Solution:
    def minFlips(self, s):
        count1=0
        count2=0
        for i in range(len(s)):
            if (i%2==0 and s[i]!="1") or (i%2!=0 and s[i]!="0"):
                count1+=1
            if (i%2==0 and s[i]!="0") or (i%2!=0 and s[i]!="1"):
                count2+=1
        return min(count1,count2)
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(|S|) and space complexity as O(1) is as follows :- 
 
Execution Time :- 0.0 / 1.3 sec
 
int minFlips (string S){   int cnt1 = 0,cnt2 = 0;   int n = S.length();   for(int i = 0; i < n; i++){       if(i & 1){           if(S[i] != '0') cnt1++;           if(S[i] != '1') cnt2++;       }       else{           if(S[i] != '1') cnt1++;           if(S[i] != '0') cnt2++;       }   }   return min(cnt1,cnt2);}
0
khunalshaik2 months ago
def minFlips(self, S):
       # initialize length and duplicate string of perfect output to compare with given string and return the result of minimum difference.
       l = len(S)
       count1 = "1"
       count2 = "0"
       
       for i in range(l-1):
       
           if i % 2 == 0 :
               count1 += "0"
               count2 += "1"
       
           else:
               count1 += "1"
               count2 += "0"
       
       diff1, diff2 = 0 , 0
       
       for i in range(len(S)):
       
           if S[i] == count1[i] :
               diff2 += 1
       
           else:
               diff1 += 1
       
       return min(diff1, diff2)
0
sunghunet2 months ago
int XOR(string bits1,string bits2){
	// return sum of 1s 

	if(bits1.length() != bits2.length())
		return -1;

	int osum = 0;
	for(int i = 0;i < bits1.length();i++) {
		if(bits1[i] != bits2[i])
			osum += 1;
	}
	return osum;
}

int minFlips(string S)
{
	string zeroFirst = "0",oneFirst = "1";
	for(int i = 2;i <= S.length();i++){
		if(i % 2 == 0) {
			zeroFirst += "1";
			oneFirst += "0";
		} else {
			zeroFirst += "0";
			oneFirst += "1";
		}
	}

	int xZero = XOR(S,zeroFirst),xOne = XOR(S,oneFirst);

	return  (xZero > xOne) ? xOne : xZero;
}
+2
manishmaheshwari81332 months ago
JAVA CODE
TC=O(|s|)
SC=O(1)
class Solution {
    public int minFlips(String S) {
        int fir=0,sec=0;

        for(int i=0;i<S.length();i++){
            if((i%2==0 && S.charAt(i)=='1')||(i%2!=0 && S.charAt(i)=='0'))fir++;
            else sec++;
        }
        
        return Math.min(fir,sec);
    }
}
 
another solution
TC=O(2|s|)
SC=O(1)
class Solution {
    public int minFlips(String S) {
        int fir=0,sec=0;
       
        
        for(int i=0;i<S.length();i++){
            if(i%2==0){
                if(S.charAt(i)!='0')fir++;
            }else{
                if(S.charAt(i)!='1')fir++;
            }
        }
        
        for(int i=0;i<S.length();i++){
            if(i%2==0){
                if(S.charAt(i)!='1')sec++;
            }else{
                if(S.charAt(i)!='0')sec++;
            }
        }
               
        return Math.min(fir,sec);
        
    }
}
+1
absaarali15482 months ago
int minFlips (string S){   int s = 0 , n = S.length();   for(int i = 0 ; i < n ; i+=2)       if(S[i]=='1')           s++;   for(int i = 1 ; i < n ; i+=2)       if(S[i]=='0')           s++;   return min(s,n-s);}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.