Minimize operations to make given binary string as all 1s by repeatedly converting K consecutive characters to 1
Given a binary string str of N characters an integer K, the task is to find the minimum moves required to convert all characters of the string to 1’s where at each move, K consecutive characters can be converted to 1.
Example:
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.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: str=”0010″, K=3
Output: 2
Explanation:
Move 1: Select the substring from 0 to 2 and replace it with all 1.
Move 2: Select the substring from 1 to 3 and replace it with all 1.Input: str=”0000010″, K=1
Output: 6
Approach: This problem can be solved using a greedy approach. To solve this problem, follow the below steps:
- Create a variable cnt, to store the minimum number of moves required. Initialize it with 0.
- Traverse the string using a variable i and str[i] = ‘0’, then update i to i + K and increase cnt by 1, because no matter what these characters are, a move is always required to convert the character str[i] to ‘1’.
- After the loop ends, return cnt which will be the required answer.
Below is the implementation of the above approach:
C++
// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// operations required to convert// the binary string str to all 1sint minMoves(string str, int K){ int N = str.size(); // Variable to store number // of minimum moves required int cnt = 0; int i = 0; // Loop to traverse str while (i < N) { // If element is '0' if (str[i] == '0') { i += K; cnt += 1; } // If element is '1' else { i++; } } return cnt;} // Driver Codeint main(){ string str = "0010"; int K = 3; cout << minMoves(str, K);} |
2
Time Complexity: O(N)
Auxiliary Space: O(1)


