


Minimum number of moves required to place all 0's before 1's in a binary string
Problem Statement
We are given a binary string str and we are asked to remove the minimum number of characters from the string so that we can put all zeros before 1's.
Example
enter
str = ‘00110100111’
Output
3
illustrate
Here, we can achieve output 3 in two ways.
We can remove arr[2], arr[3] and arr[5] or arr[4], arr[6] and arr[7] from the string.
enter
str = ‘001101011’
Output
2
illustrate
We can remove arr[4] and arr[6] and put all zeros before ones.
enter
str = ‘000111’
Output
0
illustrate
In the given string, all zeros have been placed before 1, so we don't need to remove any characters from the given string.
method 1
In the first method, we will use two arrays. The first array stores all 1's on the left and the other array stores all 0's on the right. After that, we can add the elements at i-th index in both arrays and find the minimum sum.
algorithm
Step 1 - Define a named list of "zeros" and "ones" of length n, where n is the length of the string that we can get using the size() method. < /p>
Step 2 - If the first character in the given string is "1", store 1 at the 0th index of the "ones" array; otherwise, store 0.
Step 3 - Use a for loop to start traversing from the second element of the string. In the for loop, Ones[i] is initialized with the value obtained by adding Ones[i-1] to 1 or 0 based on the character of the string at index i.
Step 4 - Store either 1 or 0 at Zeros[n-1] depending on the last character in the given string.
Step 5 - Use a for loop to traverse the string starting from the second last character and update the value of the zero list based on the string characters.
< /里>Step 6 - Define the "min_zeros_to_remove" variable and initialize it with the maximum integer value.
Step 7 - Now, loop through the "zero" and "one" lists. Access values from the "i 1" index in the zero list and the "I" index in the "one" list. After that, add these two elements.
Step 8 - If the value of "min_zeros_to_remove" is less than the current value of the "min_zeros_to_remove" variable, change its value to the sum of the two array elements.
< /里>Step 9 - Return the result value.
Example
#include <bits/stdc++.h> using namespace std; int minimumZeroRemoval(string str){ int n = str.size(); // arrays to store the prefix sums of zeros and ones vector<int> zeros(n); vector<int> ones(n); // compute total number of 1s at the left of each index ones[0] = (str[0] == '1') ? 1 : 0; for (int i = 1; i < n; i++) { ones[i] = ones[i - 1] + ((str[i] == '1') ? 1 : 0); } // compute total number of 0s at the right of each index zeros[n - 1] = (str[n - 1] == '0') ? 1 : 0; for (int i = n - 2; i >= 0; i--){ zeros[i] = zeros[i + 1] + ((str[i] == '0') ? 1 : 0); } // do the sum of zeros and ones for each index and return the minimum value int min_zeros_to_remove = INT_MAX; for (int i = 0; i < n - 1; i++){ min_zeros_to_remove = min(min_zeros_to_remove, zeros[i + 1] + ones[i]); } return min_zeros_to_remove; } int main() { string str = "00110100111"; int count = minimumZeroRemoval(str); cout << "The minimum number of zeros required to remove from the given string is - " << count; return 0; }
Output
The minimum number of zeros required to remove from the given string is - 3
Time complexity - O(N) because we need a for loop to iterate over strings and lists of size N.
Space Complexity - O(N) because we use two lists to store the counts of 1 and 0.
Method 2
This method is an optimized version of the first method. Here, instead of a list, we use two variables to store the count of 1s and 0s.
algorithm
Step 1 - Define the "zeros_right" variable and initialize it with 0.
Step 2 - Loop through the string, count the total number of "0" characters in the given string, and update the value of the "zero_right" variable accordingly. < /p>
Step 3 - Define the "ones_left" variable and initialize it to 0.
Step 4 - Use a for loop to iterate through the string. If the character at index i in the string is "1", increase the value of the "ones_left" variable by 1. Otherwise, reduce the value of the "zeros_right" variable by 1.
Step 5 - If "zeros_right Ones_left" is less than the current value of the "res" variable, update the value of the "res" variable.
Example
#include <bits/stdc++.h> using namespace std; // function to remove zeros from the string to place all zeros before 1. int minimumZeroRemoval(string str){ // counting the total number of zeros in the given string int zeros_right = 0; for (int i = 0; i < str.size(); i++) { if (str[i] == '0') zeros_right += 1; } // variable to store the number of ones from left int ones_left = 0; // Size of the string int len = str.size(); // variable to store the final result int result = INT_MAX; // Traverse the string from left to right for (int i = 0; i < len; i++){ // If the current character is '1', then increment ones_left by 1 else, decrement zeros_right by 1 if (str[i] == '1') { ones_left += 1; } else { zeros_right -= 1; } // Store the minimum result and zeros_right + ones_left in result result = min(result, zeros_right + ones_left); } // Return the final result return result; } int main() { string str = "001101011"; int count = minimumZeroRemoval(str); cout << "The minimum number of zeros required to remove from the given string is - " << count; return 0; }
Output
The minimum number of zeros required to remove from the given string is - 2
Time Complexity - O(N), when we iterate over the string.
Space Complexity - O(1) since we only use constant space.
in conclusion
The user learned two ways to remove the minimum number of characters from a given binary string. The code for the second approach is more readable because we use variables to store the count of zeros and ones instead of using a list.
The above is the detailed content of Minimum number of moves required to place all 0's before 1's in a binary string. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In this problem, we need to find the longest non-increasing subsequence of a given string. Non-increasing means that the characters are either the same or in descending order. Since binary strings only contain "0" and "1", the resulting string should either start with "1" and end with "0", or start and end with "0" or "1". To solve this problem, we will count the prefix "1" and suffix "0" at each position of the string and find the maximum sum of prefix "1" and suffix "0". Problem Statement - We are given a binary string str. We need to find the longest non-increasing subsequence from the given string. Example Input–str="010100"Output–4 illustrates the longest non-recursive

The pack() function packs data into a binary string. Syntax pack(format,args) Parameters format - the format to use. The following are possible values - a - NUL padded string A - space padded string h - hexadecimal string, low nibble first H - hexadecimal string, high nibble first c - signed char C - unsigned char s - signed short (always 16 bits, machine byte order) S - unsigned short (always 16 bits, machine byte order) n - unsigned short (always 16 bits, big endian byte order) v - unsigned short (always 16 bits, little endian byte order) i - signed integer (depends on machine size and byte order) I - None signed integer (depending on

In the given problem, we are given a string consisting of 0 and 1; we need to find the total number of all permutations starting with 1. Since the answer may be a huge number, we take it modulo 1000000007 and output it. Input:str="10101001001"Output:210Input:str="101110011"Output:56 We will solve this problem by applying some combinatorial mathematics and setting up some formulas. Solution Method In this method we will count the number of 0's and 1's. Now suppose n is the number of 1's that appear in our string and m is the number of 0's that appear in our string

Problem Statement We have a string str and a binary string B. The length of both strings is equal to N. We need to check if we can make string str a palindrome string by swapping its characters multiple times on any pair of indexes containing unequal characters in string B. Example Example Input str=‘AAS’ B=‘101’ Output ‘YES’ The Chinese translation of Explanation is: Explanation We can exchange str[1] and str[2] because B[1] and B[2] are not equal. The final string can be 'ASA'. Input str=‘AASS’ B=‘1111’ and output ‘No’. The Chinese translation of Explanation is: Explanation that we cannot make the string palindrome,

In this article, we will discuss an interesting problem related to the field of string manipulation and game theory: "Empty a binary string by removing non-empty substrings and find the player with the fewest remaining zeros". This question explores the concept of using binary strings for competitive gaming. Our goal is to find the player with the fewest 0 remaining at the end of the game. We will discuss this issue, provide a C++ code implementation, and explain the concept through an example. Understanding the problem statement Two players are given a binary string and they take turns playing the game. On each turn, the player removes non-empty substrings that contain at least one "1". The game ends when the string becomes empty or there is no "1" in the string. Players unable to take action lose the game. The task is to find the final 0

The purpose of this article is to implement a program that counts the number of binary strings of length N formed by repeated concatenation of a substring. The goal is to determine how many binary strings of length N can be created by repeatedly concatenating individual substrings of the given text, where N is a positive integer. Problem Statement Implement a program that counts the number of binary strings of length N that repeatedly concatenate substrings. Example Example 1 Letus take the Input, N = 3 Output: 2 The Chinese translation of Explanation is: Explanation The following lists feasible binary strings of length N = 3, in which a substring is repeatedly concatenated. "000":Thesubstr

Given two binary strings str1 and str2 of the same length, we have to maximize the given function value by selecting substrings from the given strings of the same length. The given function is like this - fun(str1,str2)=(len(substring))/(2^xor(sub1,sub2)). Here, len(substring) is the length of the first substring and xor(sub1,sub2) is the XOR of the given substring, this is possible since they are binary strings. Example Input1:stringstr1=10110&stringstr2=11101Output:3 illustrates our

Problem Statement We are given a binary string str and we are required to remove minimum characters from the string so that we can place all zeros before ones. Example input str=‘00110100111’ Output 3 Description Here, we can achieve output 3 in two ways. We can remove arr[2], arr[3] and arr[5] or arr[4], arr[6] and arr[7] from the string. Input str=‘001101011’ and output 2 shows that we can delete arr[4] and arr[6] and put all zeros before 1. Input str=‘000111’ Output 0 means that in the given string, all zeros have been placed before 1, so we don’t need to start from
