Given a binary string str of length N and an integer K where K is in the range (1 ≤ K ≤ N), the task is to find the minimum number of flips( conversion of 0s to 1 or vice versa) required to be performed on the given string such that the resulting string does not contain K or more zeros together.
Input: str = “11100000011”, K = 3
Flipping 6th and 7th characters modifies the string to “11100110011”.
Therefore, no substring of 0s are present in the string having length 3 or more.
Input: str = “110011”, K = 1
Flip 3rd and 4th characters then str = “111111” which does not contain 1 or more zeros together.
Naive Approach: The simplest approach is to generate all possible substrings of the given string and for each substring, check if it consists of only 0s or not. If found to be true, check if its length exceeds K or not. If found to be true, count the number of flips required for that substring. Finally, print the count of flips obtained.
Time Complexity: O(2N)
Auxiliary Space: O(N)
Efficient Approach: To make the count of contiguous zeros in resultant string less than K, choose the substrings consisting of only zeros of length ≥ K. So the problem reduces to finding the minimum flips in each substring. The final result will be the sum of minimum flips of all such subsegments. Below are the steps:
- Initialize the result to 0and the count of contiguous zeros (say cnt_zeros) to 0.
- Transverse the string and on encountering a ‘0’ increment cnt_zeros by 1.
- If cnt_zeros becomes equal to K then increment result and set cnt_zeros to 0.
- And when a ‘1’ comes then set cnt_zeros to 0 since the count of contiguous zeros should become 0.
Below the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
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.