 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 and S, modifies the string to 1110000, thus, maximizing the number that can be generated from the string.

Input:_ S = “110001001”_

Output:_ 2_

_Explanation: _Swapping S with S and S with S, 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, …, 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

## Buddha Community  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 and S, modifies the string to 1110000, thus, maximizing the number that can be generated from the string.

Input:_ S = “110001001”_

Output:_ 2_

_Explanation: _Swapping S with S and S with S, 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, …, 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 1595354400

## Minimum number of distinct powers of 2 required to express a given binary number

Given a binary string S, the task is to find the minimum number of Powers of 2 required to express a S.

Examples:

Input:_ S = “111”_

Output:_ 2_

Explanation:

Two possible representations of “111” (= 7) using powers of 2 are:

20 + 21 + 22 = 1 + 2 + 4 = 7

23 – 20 = 8 – 1 = 7

Therefore, the minimum powers of 2 required to represent S is 2.

Input:_ S = “1101101”_

Output:_ 4_

Explanation:

1101101 can be represented as 27 – 24 – 22 + 20.

Approach:

The key observation to solve this problem is that we can replace any consecutive sequence of 1 by using only two powers of 2.

Illustration:

S = “1001110”

The sequence of 3 consecutive 1’s, “1110” can be expressed as 24 – 21

Therefore, the given str

Follow the steps below to solve the problem:

• Reverse the string S.
• Iterate over the string S.
• Replace every substring of 1’s lying within indices [L, R] by placing 1 at R+1 and -1 at L.
• Once the entire string is traversed, count the number of non-zero values in the string as the required answer.

Below is the implementation of the above approach:

• C++

filter_none

edit

play_arrow

brightness_4

`// C++ Program to implement the`

`// above approach`

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

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

`// Function to return the minimum`

`// distinct powers of 2 required`

`// to express s`

`**void**` `findMinimum(string s)`

`{`

`**int**` `n = s.size();`

`**int**` `x[n + 1] = { 0 };`

`// Reverse the string to`

`// start from lower powers`

`reverse(s.begin(), s.end());`

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

`// Check if the character is 1`

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

`**if**` `(x[i] == 1) {`

`x[i + 1] = 1;`

`x[i] = 0;`

`}`

`// Add in range provided range`

`**else**` `**if**` `(i and x[i - 1] == 1) {`

`x[i + 1] = 1;`

`x[i - 1] = -1;`

`}`

`**else**`

`x[i] = 1;`

`}`

`}`

`// Initialize the counter`

`**int**` `c = 0;`

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

`// Check if the character`

`// is not 0`

`**if**` `(x[i] != 0)`

`// Increment the counter`

`c++;`

`}`

`// Print the result`

`cout << c << endl;`

`}`

`// Driver Code`

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

`{`

`string str =` `"111"``;`

`findMinimum(str);`

`**return**` `0;`

`}`

Output:

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

#arrays #competitive programming #greedy #mathematical #strings #binary-string #substring 1624005780

## Java: Check if String is a Number

#### Introduction

Strings are a handy way of getting information across and getting input from a user.

In this article, we will go through a couple of ways check if a String is Numeric in Java - that is to say, if a String represents a numeric value.

#### Check if String is Numeric with Regex

#java #apache commons #java: check if string is a number #check if string is a number #string 1619565060

## Ternary operator in Python?

1. Ternary Operator in Python

What is a ternary operator: The ternary operator is a conditional expression that means this is a comparison operator and results come on a true or false condition and it is the shortest way to writing an if-else statement. It is a condition in a single line replacing the multiline if-else code.

syntax : condition ? value_if_true : value_if_false

condition: A boolean expression evaluates true or false

value_if_true: a value to be assigned if the expression is evaluated to true.

value_if_false: A value to be assigned if the expression is evaluated to false.

How to use ternary operator in python here are some examples of Python ternary operator if-else.

Brief description of examples we have to take two variables a and b. The value of a is 10 and b is 20. find the minimum number using a ternary operator with one line of code. ( **min = a if a < b else b ) **. if a less than b then print a otherwise print b and second examples are the same as first and the third example is check number is even or odd.

#python #python ternary operator #ternary operator #ternary operator in if-else #ternary operator in python #ternary operator with dict #ternary operator with lambda 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.