VOOZH about

URL: https://www.geeksforgeeks.org/dsa/make-all-ones-together-by-shifting-ones/

⇱ Make all Ones together by Shifting Ones. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Make all Ones together by Shifting Ones.

Last Updated : 29 Jan, 2024

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:

  • Initialize a variable countOnes and store a total number of ones in the string.
  • Initialize a variable ans which will store the final result.
  • Now iterate over the string and at every occurrence of zero characters make a decision either to move left or right, take the minimum from it, and add it to the ans.
  • If the current character is '1'. Increment leftOnes and right ones can be calculated by countOnes - leftOnes, which will store the left side one character count.
  • Return the final result stored in ans.

Implementation of the above approach:


Output
2

Time complexity: O(n). Where n is the length of binary string.
Auxiliary space: O(1). Since there is no extra space used.

Comment
Article Tags: