Minimum number of flips to make a Binary String increasing
Given a binary string S, the task is to find the minimum number of characters the needed to be flipped to make the given binary string increasing.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: S = “00110”
Explanation: Flip S = ‘0’ to ‘1’ of the string modifies the given string to “00111”. Therefore, the minimum number of flips required is 1.
Input: S = “010110”
Approach: The given problem can be solved by using a Greedy Algorithm based on the observations that the resultant monotonically increasing string after any number of flips will be of the form (‘0’*p + ‘1’*q), where p and q are the count of 0s and 1s respectively in the modified string. The idea is to traverse the given string S and for each index, i modify the substring S[0, i) to 0s and substring S[i, N) to 1s and find the minimum flips required accordingly. Follow the steps below to solve the problem:
- Find the count of 0s in the given binary string S and store it in a variable countZero.
- Initialize variable, say minFlips as (N – cntZero) that stores the minimum number of flips required.
- Initialize variable, say cntOne as 0 that stores the count of 1s in the string while traversing the string.
- Traverse the given string S and perform the following steps:
- If the character S[i] is 0, then decrement the value of countZero by 1.
- Otherwise, update the value of minFlips as the minimum of minFlips and (countZero + countOne) and increment the value of countOne by 1.
- After completing the above steps, print the value of minFlips as the result.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(1)