![]() |
VOOZH | about |
Given, a binary string contains zeroes and ones. In one operation you can move one step character '1' to either left or right. Find the minimum number of operations required to make all ones together without any intermediate zeroes.
Examples:
Input: 11011
Output: 2
Explanation: In the first operation move '1' at index 3 to index 2. Now the string becomes 11101. In the second operation move '1' at index 4 to index 3. Now the string becomes 11110. Therefore, the answer is 2.Input: 100
Output: 0
Explanation: Since there is only one '1 in the string there are no operations to make.
Approach: To solve the problem follow the below idea.
This problem can be solved using a greedy approach. According to the problem in one operation, we can character '1' to either right or left. So we will traverse the binary string s whenever there is character '0' we will make a decision whether to bring all the character '1''s before the zero or all the character '1' after the zero. We can simply find a minimum of these two and increment the answer. We will continue doing this for every occurrence of zero characters.
Steps to Implement the Approach:
Implementation of the above approach:
2
Time complexity: O(n). Where n is the length of binary string.
Auxiliary space: O(1). Since there is no extra space used.