Open In App

Make all Ones together by Shifting Ones.

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




#include <iostream>
 
using namespace std;
 
// function to return final result
int makeAllOnesTogether(string s)
{
    int n = s.size();
 
    // variable to store count one's
    int countOnes = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] == '1')
            countOnes += 1;
    }
 
    // to store final answer.
    int ans = 0;
 
    // to count left side one'susing System;
 
public class Stack
{
    // Indices to keep track of the front, rear, and size of the queue
    private int front, rear, size;
 
    // Maximum capacity of the queue
    private readonly int capacity;
 
    // Array to store the elements
    private int[] arr;
 
    public Stack(int capacity)
    {
        this.capacity = capacity;
 
        // Initially, front index and size are set to 0
        front = size = 0;
 
        // Rear index is set to the last index of the array
        rear = capacity - 1;
 
        // Dynamic allocation of memory for the array
        arr = new int[this.capacity];
    }
 
    public bool IsFull()
    {
        // If size is equal to the capacity, the stack is full
        return (size == capacity);
    }
 
    public bool IsEmpty()
    {
        // If size is 0, the stack is empty
        return (size == 0);
    }
 
    public void Push(int x)
    {
        if (IsFull())
        {
            // If the stack is full, return without adding the element
            return;
        }
 
        // Increase the rear index by 1 (with wraparound)
        rear = (rear + 1) % capacity;
 
        // Add the element to the rear position
        arr[rear] = x;
 
        // Increase the size of the stack by 1
        size++;
    }
 
    public void Pop()
    {
        if (IsEmpty())
        {
            return; // If the stack is empty, return without doing anything
        }
 
        // Decrease the rear index by 1 (with wraparound)
        rear = (rear - 1 + capacity) % capacity;
 
        // Decrease the size of the stack by 1
        size--;
    }
 
    public int Top()
    {
        if (IsEmpty())
        {
            // If the stack is empty, return -1
            return -1;
        }
 
        // Return the element at the rear position
        return arr[rear];
    }
 
    public int GetSize()
    {
        // Return the current size of the stack
        return size;
    }
}
 
public class MainClass
{
    public static void Main()
    {
        // Create a stack of maximum size 3
        Stack s = new Stack(3);
 
        s.Push(1);
        s.Push(2);
        s.Push(3);
 
        Console.WriteLine("current size: " + s.GetSize());
        Console.WriteLine(s.Top());
        s.Pop();
        Console.WriteLine(s.Top());
        s.Pop();
        Console.WriteLine(s.Top());
 
        Console.WriteLine("current size: " + s.GetSize());
    }
}
 
    int leftOnes = 0;
 
    for (int i = 0; i < n; i++) {
        if (s[i] == '0') {
            // minimum of left side one's or right side
            // one's
            ans += min(leftOnes, countOnes - leftOnes);
        }
        // increment leftOnes if present character is one.
        if (s[i] == '1')
            leftOnes += 1;
    }
 
    return ans;
}
 
int main()
{
    string s = "11011";
    // function call
    cout << makeAllOnesTogether(s);
    return 0;
}


Java




import java.util.Scanner;
 
public class GFG {
 
    // function to return final result
    static int makeAllOnesTogether(String s) {
        int n = s.length();
        int countOnes = 0;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == '1')
                countOnes += 1;
        }
 
        int ans = 0;
        int leftOnes = 0;
 
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == '0') {
                ans += Math.min(leftOnes, countOnes - leftOnes);
            }
            if (s.charAt(i) == '1')
                leftOnes += 1;
        }
 
        return ans;
    }
 
    public static void main(String[] args) {
        String s ="11011";
 
        // function call
        System.out.println(makeAllOnesTogether(s));
    }
}


Python3




# Python Implementation
def make_all_ones_together(s):
    n = len(s)
    count_ones = s.count('1')
    ans = 0
    left_ones = 0
 
    for i in range(n):
        if s[i] == '0':
            ans += min(left_ones, count_ones - left_ones)
        if s[i] == '1':
            left_ones += 1
 
    return ans
 
s = "11011"
print(make_all_ones_together(s))
 
# This code is contributed by Sakshi


C#




using System;
 
public class MainClass
{
    // Function to return the final result
    static int MakeAllOnesTogether(string s)
    {
        int n = s.Length;
 
        // Variable to store count of ones
        int countOnes = 0;
        for (int i = 0; i < n; i++)
        {
            if (s[i] == '1')
                countOnes += 1;
        }
 
        // To store the final answer.
        int ans = 0;
 
        // To count left side ones
        int leftOnes = 0;
 
        for (int i = 0; i < n; i++)
        {
            if (s[i] == '0')
            {
                // Minimum of left side ones or right side ones
                ans += Math.Min(leftOnes, countOnes - leftOnes);
            }
 
            // Increment leftOnes if the present character is one.
            if (s[i] == '1')
                leftOnes += 1;
        }
 
        return ans;
    }
 
    public static void Main()
    {
        string s = "11011";
        // Function call
        Console.WriteLine(MakeAllOnesTogether(s));
    }
}


Javascript




function makeAllOnesTogether(s) {
    const n = s.length;
    let countOnes = 0;
 
    // Count the number of ones
    // in the string
    for (let i = 0; i < n; i++) {
        if (s[i] === '1') {
            countOnes++;
        }
    }
 
    let ans = 0;
     
    // to count left side one's
    let leftOnes = 0;
 
    for (let i = 0; i < n; i++) {
        if (s[i] === '0') {
            // Calculate the minimum of left
            // side ones or right side ones
            ans += Math.min(leftOnes, countOnes - leftOnes);
        }
        // Increment leftOnes if the
        // current character is '1'
        if (s[i] === '1') {
            leftOnes++;
        }
    }
 
    return ans;
}
 
const s = "11011";
// Function call
console.log(makeAllOnesTogether(s));


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads