You are given a binary string of even length and equal number of 0’s and 1’s. What is the minimum number of swaps to make the string alternating. A binary string is alternating if no two consecutive elements are equal.
Input : 000111 Output : 1 Explanation : Swap index 2 and index 5 to get 010101 Input : 1010 Output : 0
We may either get a 1 at first position or a zero at first position. We consider two cases and find the minimum of two cases. Note that it is given that there are equal of numbers of 1’s and 0’s in the string and string is of even length.
1. Count number of zeroes at odd position and even position of the string. Let their count be odd_0 and even_0 respectively.
2. Count number of ones at odd position and even position of the string. Let their count be odd_1 and even_1 respectively.
3. We will always swap a 1 with a 0 (never a 1 with a 1 or a 0 with a 0). So we just check if our alternating string starts with 0 then the number of swaps is min(even_0, odd_1) and if our alternating string starts with 1 then the number of swaps is min(even_1, odd_0). The answer is min of these two .
Below is the implementation of above approach:
- Minimum swaps required to make a binary string divisible by 2^k
- Minimum swaps required to convert one binary string to another
- Minimum number of replacements to make the binary string alternating | Set 2
- Minimum number of swaps to make two binary string equal
- Minimum adjacent swaps required to Sort Binary array
- Minimum changes required to make first string substring of second string
- Minimum operations required to make the string satisfy the given condition
- Minimum given operations required to convert a given binary string to all 1's
- Minimum number of operations required to sum to binary string S
- Minimum operations required to convert a binary string to all 0s or all 1s
- Minimum number of characters to be removed to make a binary string alternate
- Minimum changes required to make all element in an array equal
- Minimum number of pairs required to make two strings same
- Minimum deletions required to make GCD of the array equal to 1
- Minimum array insertions required to make consecutive difference <= K
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.