1595970000

# Minimum size binary string required such that probability

Given a value X, the task is to find a minimum size binary string, such that if any 2 characters are deleted at random, the probability that both the characters will be ‘1’ is 1/X. Print the size of such binary string.

Example:

Input:_ X = 2_

Output:_ 4_

Explanation:

Let the binary string be “0111”.

Probability of choosing 2 1s from given string is = 3C2 / 4C2 = 3/6 = 1/2 (which is equal to 1/X).

Hence the required size is 4.

(Any 4 size binary string with 3 ‘1’s and 1 ‘0’ can be taken for this example).

Input:_ X = 8_

Output:_ 5_

Approach: We will try to find a formula to solve this problem.

Let

r = Number of 1’s in the string

and

b = Number of 0’s in the string.

• If two characters are deleted at random, then

Total number of ways = (r + b) C 2.

• If 2 characters are desired to be 1’s, Favourable number of cases = r C 2.
• Hence, P(both are 1’s) = rC2 / (r + b)C2.

Below is the implementation of the above approach.

## C++

`// C++ implementation of the`

`// above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function returns the minimum`

`// size of the string`

`**int**` `MinimumString(``**int**` `x)`

`{`

`// From formula`

`**int**` `b = 1;`

`// Left limit of r`

`**double**` `left_lim =` `**sqrt**``(x) + 1.0;`

`// Right limit of r`

`**double**` `right_lim =` `**sqrt**``(x) + 2.0;`

`**int**` `r;`

`**for**` `(``**int**` `i = left_lim; i <= right_lim; i++) {`

`**if**` `(i > left_lim and i < right_lim) {`

`// Smallest integer in`

`// the valid range`

`r = i;`

`**break**``;`

`}`

`}`

`**return**` `b + r;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `X = 2;`

`cout << MinimumString(X);`

`**return**` `0;`

`}`

Output:

``````4
``````

Time Complexity: O(1), as the difference between left_lim and right_lim will be always less than 1.

Auxiliary Space: O(1)

#combinatorial #competitive programming #mathematical #binary-string #probability #arrays

1595970000

## Minimum size binary string required such that probability

Given a value X, the task is to find a minimum size binary string, such that if any 2 characters are deleted at random, the probability that both the characters will be ‘1’ is 1/X. Print the size of such binary string.

Example:

Input:_ X = 2_

Output:_ 4_

Explanation:

Let the binary string be “0111”.

Probability of choosing 2 1s from given string is = 3C2 / 4C2 = 3/6 = 1/2 (which is equal to 1/X).

Hence the required size is 4.

(Any 4 size binary string with 3 ‘1’s and 1 ‘0’ can be taken for this example).

Input:_ X = 8_

Output:_ 5_

Approach: We will try to find a formula to solve this problem.

Let

r = Number of 1’s in the string

and

b = Number of 0’s in the string.

• If two characters are deleted at random, then

Total number of ways = (r + b) C 2.

• If 2 characters are desired to be 1’s, Favourable number of cases = r C 2.
• Hence, P(both are 1’s) = rC2 / (r + b)C2.

Below is the implementation of the above approach.

## C++

`// C++ implementation of the`

`// above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function returns the minimum`

`// size of the string`

`**int**` `MinimumString(``**int**` `x)`

`{`

`// From formula`

`**int**` `b = 1;`

`// Left limit of r`

`**double**` `left_lim =` `**sqrt**``(x) + 1.0;`

`// Right limit of r`

`**double**` `right_lim =` `**sqrt**``(x) + 2.0;`

`**int**` `r;`

`**for**` `(``**int**` `i = left_lim; i <= right_lim; i++) {`

`**if**` `(i > left_lim and i < right_lim) {`

`// Smallest integer in`

`// the valid range`

`r = i;`

`**break**``;`

`}`

`}`

`**return**` `b + r;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `X = 2;`

`cout << MinimumString(X);`

`**return**` `0;`

`}`

Output:

``````4
``````

Time Complexity: O(1), as the difference between left_lim and right_lim will be always less than 1.

Auxiliary Space: O(1)

#combinatorial #competitive programming #mathematical #binary-string #probability #arrays

1597460400

## Minimum number of operations required to maximize the Binary String

Given a binary string S, the task is to find the minimum number of swaps required to be performed to maximize the value represented by S.

Examples:

_Input: _S = “1010001”

Output:_ 1_

_Explanation: _Swapping S[2] and S[7], modifies the string to 1110000, thus, maximizing the number that can be generated from the string.

Input:_ S = “110001001”_

Output:_ 2_

_Explanation: _Swapping S[3] with S[6] and S[4] with S[9], we get 111100000 which is the required string

Naive Approach:

It can be observed that, in order to maximize the required string, the characters should be swapped such that all 0s should be on the right and all the 1s are on the left. Therefore, the string needs to be modified to a “1…10…0” sequence.

Follow the below steps to solve the problem:

1. Count the number of 1s in the string S, say cnt1.
2. Count the number of 0s in substring S[0], …, S[cnt1-1], say cnt0.
3. Print cnt0 as the required answer.

Below is the implementation of above approach:

• C++

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function to find the number`

`// of operations required`

`**int**` `minOperation(string s,` `**int**` `n)`

`{`

`// Count of 1's`

`**int**` `cnt1 = 0;`

`**for**` `(``**int**` `i = 0; i < n; i++) {`

`**if**` `(s[i] ==` `'1'``)`

`cnt1++;`

`}`

`// Count of 0's upto (cnt1)-th index`

`**int**` `cnt0 = 0;`

`**for**` `(``**int**` `i = 0; i < cnt1; i++) {`

`**if**` `(s[i] ==` `'0'``)`

`cnt0++;`

`}`

`// Return the answer`

`**return**` `cnt0;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `n = 8;`

`string s =` `"01001011"``;`

`**int**` `ans = minOperation(s, n);`

`cout << ans << endl;`

`}`

Output:

``````3
``````

Time Complexity:_ O(N)_

Auxiliary Space:_ O(1)_

Efficient Approach:

The above approach can be further optimized using Two Pointers technique. Follow the below steps to solve the problem:

• Set two pointers **i = 0 **and j = S.length() – 1 and iterate until i exceeds j.

• Increase count, if S[i] is equal to ‘0‘ and S[j] is equal to ‘1‘.

• Increment i if S[i] is ‘1‘ until a ‘0‘ appears. Similarly, decrease **j **until S[j] is equal to ‘1‘.

• Print count as the required answer.

• Below is the implementation of above approach:

• C++

• `// C++ Program to implement`

• `// the above approach`

• `#include <bits/stdc++.h>`

• `**using**` `**namespace**` `std;`

• `// Function to find the number`

• `// of operations required`

• `**int**` `minOperation(string s,` `**int**` `n)`

• `{`

• `**int**` `ans = 0;`

• `**int**` `i = 0, j = n - 1;`

• `**while**` `(i < j) {`

• `// Swap 0's and 1's`

• `**if**` `(s[i] ==` `'0'` `&& s[j] ==` `'1'``) {`

• `ans++;`

• `i++;`

• `j--;`

• `**continue**``;`

• `}`

• `**if**` `(s[i] ==` `'1'``) {`

• `i++;`

• `}`

• `**if**` `(s[j] ==` `'0'``) {`

• `j--;`

• `}`

• `}`

• `// Return the answer`

• `**return**` `ans;`

• `}`

• `// Driver Code`

• `**int**` `main()`

• `{`

• `**int**` `n = 8;`

• `string s =` `"10100101"``;`

• `**int**` `ans = minOperation(s, n);`

• `cout << ans << endl;`

• `}`

• Output:

``````2
``````
• Time Complexity:_ O(N)_
• Auxiliary Space:_ O(1)_
• 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.

#greedy #searching #strings #binary-string #frequency-counting #two-pointer-algorithm

1603818000

## Minimum substring flips required to convert given binary string to another

Given two binary strings A and B, the task is to find the minimum number of times a substring starting from the first character of A needs to be flipped, i.e. convert 1s to** 0**s and 0s to 1s, to convert A to B.

Examples:

Input:_ A = “0010”, B = “1011”_

Output;_ 3_

Explanation:

Step 1: Flip the entire string A. Therefore, A becomes “1101” .

Step 2: Flip the substring {A[0], A[2]}. Therefore, A becomes “0011” .

Step 3: Flip A[0]. Therefore, A becomes “1011” which is equal to B.

Therefore, the minimum number of operations required is 3.

Input:_ A = “1010101”, B = “0011100”_

Output:_ 5_

Explanation:

Step 1: Flip the entiThehrefore, A becomes “0101010″

Step 2: Flip substring {A[0], A[5]}. Therefore, A becomes “1010100″

Step 3: Flip the substring {A[0], A[3]}. Therefore, A becomes “0101100″

Step 4: Flip the substring {A[0], A[2]}. Therefore, A becomes “1011100″

Step 5: Flip A[0]. Therefore, A becomes “0011100” which is equal to B.

Therefore, the minimum number of operations required is 5.

Approach: The idea is to initialize a** variable** that holds the last index at which character at A is different from the character at B. Then negate A from the 1st index to the last index. Repeat until both strings become equal. Follow the steps below to solve the problem:

• Initialize a variable **last_index **that holds the last index at which characters are different in A and B.
• Negate string A from the 1st index to last_index and increment the count of steps.
• Repeat the above steps until string A becomes equal to string B.
• Print the count of steps after both the strings are the same after performing the operations.

Below is the implementation of the above approach:

### C++

`// C++ program for the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function that finds the minimum`

`// number of operations required such`

`// that string A and B are the same`

`**void**` `findMinimumOperations(string a,`

`string b)`

`{`

`// Stores the count of steps`

`**int**` `step = 0;`

`// Stores the last index whose`

`// bits are not same`

`**int**` `last_index;`

`// Iterate until both string`

`// are unequal`

`**while**` `(a != b) {`

`// Check till end of string to`

`// find righmost unequals bit`

`**for**` `(``**int**` `i = 0;`

`i < a.length(); i++) {`

`// Update the last index`

`**if**` `(a[i] != b[i]) {`

`last_index = i;`

`}`

`}`

`// Flipping characters up`

`// to the last index`

`**for**` `(``**int**` `i = 0;`

`i <= last_index; i++) {`

`// Flip the bit`

`a[i] = (a[i] ==` `'0'``) ?` `'1'` `:` `'0'``;`

`}`

`// Increasing steps by one`

`step++;`

`}`

`// Print the count of steps`

`cout << step;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`// Given strings A and B`

`string A =` `"101010"``, B =` `"110011"``;`

`// Function Call`

`findMinimumOperations(A, B);`

`**return**` `0;`

`}`

Output:

``````4
``````

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

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.

#greedy #searching #strings #binary-string #substring

1595939220

## Minimum flips required to convert given string into concatenation of equal

Given a binary string **S **and an integer K, the task is to find the minimum number of flips required to convert the given string into a concatenation of K-length equal sub-strings. It is given that the given string can be split into K-length substrings.

Examples:

Input:_ S = “101100101”, K = 3 _

Output:_ 1 _

Explanation:

_Flip the ‘0’ at index 5 to ‘1’. _

_The resultant string is S = “101101101”. _

_It is the concatenation of substring “101”. _

Hence, the minimum number of flips required is 1.

Input:_ S = “10110111”, K = 4 _

Output:_ 2 _

Explanation:

_Flip the ‘0’ and ‘1’ at index 4 and 5 respectively. _

_The resultant string is S = “10111011”. _

_It is the concatenation of the substring “1011”. _

_Hence, the minimum number of flips required is 2. _

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

The problem can be solved using Greedy Approach.

• Iterate the given string with increments by K indices from each index and keep a count of the 0s and 1s.
• The character which occurs the minimum number of times must be flipped and keep incrementing that count.
• Perform the above steps for all the indices from 0 to K-1 to obtain the minimum number of flips required.

Below is the implementation of the above approach:

• C++

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function that returns the minimum`

`// number of flips to convert`

`// the s into a concatenation`

`// of K-length sub-string`

`**int**` `minOperations(string S,` `**int**` `K)`

`{`

`// Stores the result`

`**int**` `ans = 0;`

`// Iterate through string index`

`**for**` `(``**int**` `i = 0; i < K; i++) {`

`// Stores count of 0s & 1s`

`**int**` `zero = 0, one = 0;`

`// Iterate making K jumps`

`**for**` `(``**int**` `j = i;`

`j < S.size(); j += K) {`

`// Count 0's`

`**if**` `(S[j] ==` `'0'``)`

`zero++;`

`// Count 1's`

`**else**`

`one++;`

`}`

`// Add minimum flips`

`// for index i`

`ans += min(zero, one);`

`}`

`// Return minimum number`

`// of flips`

`**return**` `ans;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`string S =` `"110100101"``;`

`**int**` `K = 3;`

`cout << minOperations(S, K);`

`**return**` `0;`

`}`

Output:

``````2
``````

_Time Complexity: __O(N) _

_Auxiliary Space: _O(1)

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.

#greedy #mathematical #pattern searching #searching #strings #binary-string #substring

1598551200

## Minimum number of flips with rotation to make binary string alternating

Given a binary string S of 0s and 1s. The task is to make the given string a sequence of alternate characters by using the below operations:

• Remove some prefix from the start and append it to the end.
• Flip some or every bit in the given string.

Print the minimum number of bits to be flipped to make the given string alternating.

Examples:

Input:_ S = “001”_

Output:_ 0_

Explanation:

No need to flip any element we can get alternating sequence by using left rotation: 010.

Input:_ S = “000001100”_

Output:_ 3_

Explanation:

Following steps to find minimum flips to get alternating string:

_1. After rotating string 6 times towards left we will get: 100000001 _

2. Now we can apply flip operation as following: 101000001 -> 101010001 -> 101010101

Thus, minimum flips to make string alternating is 3.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The naive approach is to take all N possible combinations and calculate the minimum number of bits To flip in each of those strings. Print the minimum count among all such combinations.

Time Complexity:_ O(N2), where N is the length of the string._

Auxiliary Space:_ O(N)_

Efficient Approach: This can be solved by observing that the final string will be either of type “101010…” or “010101…” such that all 1s will either be at odd positions or at even positions. Follow the below steps to solve the problem:

1. Create a prefix sum array where pref[i] means a number of changes required until index i.
2. Create prefix arrays for both the above patterns.
3. Check for every i, if substring[0, i] is appended at the end how many characters to be flipped required.
4. Print the minimum number of flips among all the substrings in the above steps.

Below is the implementation of the above approach:

• Java
• Python3

`// Java program for the above approach`

`**import**` `java.util.*;`

`**class**` `GFG {`

`// Function that finds the minimum`

`// number of flips to make the`

`// binary string alternating if`

`// left circular rotation is allowed`

`**static**` `**int**` `MinimumFlips(String s,` `**int**` `n)`

`{`

`**int**``[] a =` `**new**` `**int**``[n];`

`**for**` `(``**int**` `i =` `0``; i < n; i++) {`

`a[i] = (s.charAt(i) ==` `'1'` `?` `1` `:` `0``);`

`}`

`// Initialize prefix arrays to store`

`// number of changes required to put`

`// 1s at either even or odd position`

`**int**``[] oddone =` `**new**` `**int**``[n +` `1``];`

`**int**``[] evenone =` `**new**` `**int**``[n +` `1``];`

`oddone[``0``] =` `0``;`

`evenone[``0``] =` `0``;`

`**for**` `(``**int**` `i =` `0``; i < n; i++) {`

`// If i is odd`

`**if**` `(i %` `2` `!=` `0``) {`

`// Update the oddone`

`// and evenone count`

`oddone[i +` `1``]`

`= oddone[i]`

`+ (a[i] ==` `1` `?` `1` `:` `0``);`

`evenone[i +` `1``]`

`= evenone[i]`

`+ (a[i] ==` `0` `?` `1` `:` `0``);`

`}`

`// Else i is even`

`**else**` `{`

`// Update the oddone`

`// and evenone count`

`oddone[i +` `1``]`

`= oddone[i]`

`+ (a[i] ==` `0` `?` `1` `:` `0``);`

`evenone[i +` `1``]`

`= evenone[i]`

`+ (a[i] ==` `1` `?` `1` `:` `0``);`

`}`

`}`

`// Initialize minimum flips`

`**int**` `minimum = Math.min(oddone[n],`

`evenone[n]);`

`// Check if substring[0, i] is`

`// appended at end how many`

`// changes will be required`

`**for**` `(``**int**` `i =` `0``; i < n; i++) {`

`**if**` `(n %` `2` `!=` `0``) {`

`minimum = Math.min(minimum,`

`oddone[n]`

`- oddone[i +` `1``]`

`+ evenone[i +` `1``]);`

`minimum = Math.min(minimum,`

`evenone[n]`

`- evenone[i +` `1``]`

`+ oddone[i +` `1``]);`

`}`

`}`

`// Return minimum flips`

`**return**` `minimum;`

`}`

`// Driver Code`

`**public**` `**static**` `**void**` `main(String[] args)`

`{`

`// Given String`

`String S =` `"000001100"``;`

`// Length of given string`

`**int**` `n = S.length();`

`// Function call`

`System.out.print(MinimumFlips(S, n));`

`}`

`}`

Output:

``````3
``````

Time Complexity:_ O(N), where N is the length of the given string._

Auxiliary Space:_ O(N)_

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.