Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped.
Input : str = “001” Output : 1 Minimum number of flips required = 1 We can flip 1st bit from 0 to 1 Input : str = “0001010111” Output : 2 Minimum number of flips required = 2 We can flip 2nd bit from 0 to 1 and 9th bit from 1 to 0 to make alternate string “0101010101”.
Expected time complexity : O(n) where n is length of input string.
We can solve this problem by considering all possible results, As we are supposed to get alternate string, there are only 2 possibilities, alternate string starting with 0 and alternate string starting with 1. We will try both cases and choose the string which will require minimum number of flips as our final answer.
Trying a case requires O(n) time in which we will loop over all characters of given string, if current character is expected character according to alternation then we will do nothing otherwise we will increase flip count by 1. After trying strings starting with 0 and starting with 1, we will choose the string with minimum flip count.
Total time complexity of solution will be O(n)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum number of characters to be removed to make a binary string alternate
- Find if it is possible to make a binary string which contanins given number of "0", "1" , "01" and "10" as sub sequences
- Minimum number of replacements to make the binary string alternating | Set 2
- Min flips of continuous characters to make all characters same in a string
- Number of ways to make binary string of length N such that 0s always occur together in groups of size K
- Check if it is possible to rearrange a binary string with alternate 0s and 1s
- Rearrange a binary string as alternate x and y occurrences
- Minimum flips to make all 1s in left and 0s in right | Set 2
- Deletions of "01" or "10" in binary string to make it free from "01" or "10"
- Count of operations to make a binary string"ab" free
- Minimum swaps required to make a binary string alternating
- Minimum number of moves to make a binary array K periodic
- Minimum number of deletions to make a string palindrome
- Minimum number of deletions to make a string palindrome | Set 2
- Number of Counterclockwise shifts to make a string palindrome