Given a binary string S with an even size containing only 0 seconds and 1s, the task is to find the minimum flips (i.e. 0 to 1 or 1 to 0) such that each contiguous subsegment containing the same bits is an even size.
Example:
Enter: S = “1110011000”
Output: 3
Explanation: Change S[2]S[5] and S[6] to ‘0’.
After that S becomes “110000000000”, can be divided into
“11” and “00000000”, which have lengths of 2 and 8, respectively.
There are other ways to operate 3 times like
“1111110000”, “1100001100”, “1111001100”.Enter: 100110
Output: 3
Explanation: The given string can be converted to 000000
with 3 operations or 111111.
Approach: To solve the problem follow the observations below:
It can be said that we have to split the string into many contiguous binaries of length 2 where the string will be either 00 or 11. So we only need to take care of the order in which s[i] != s[i+1]
- Now to find the minimum order of operations like “1011” must be changed to “1111” and “0100” must be changed to “0000”.
- So, the minimum number of operations is 1. Therefore, after we make s[i] = s[i + 1] we will move i to i+2 to check if they are equal or not.
Follow the steps mentioned below to implement the idea:
- Repeat from i = 0 to N-1:
- Check if S[i] together with S[i+1].
- If they are the same then there is no need for a slight flip.
- If not, increase the number of flips by 1.
- After each check moved from I to me+2.
- The total number of flips counted is the minimum answer required.
Below is the implementation of the above approach:
C++14
|
Time complexity: ON)
Help Room: O(1)