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 convert one binary string to another
- Minimum number of replacements to make the binary string alternating | Set 2
- Minimum adjacent swaps required to Sort Binary array
- Minimum changes required to make first string substring of second string
- Minimum number of operations required to sum to binary string S
- Minimum number of characters to be removed to make a binary string alternate
- Minimum number of given operations required to make two strings equal
- Minimum array insertions required to make consecutive difference <= K
- Operations required to make the string empty
- Find the minimum number of preprocess moves required to make two strings equal
- Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
- Minimum number of given operations required to convert a string to another string
- Minimum rotations required to get the same string
- Minimum changes required such that the string satisfies the given condition
- Minimum number of moves to make a binary array K periodic
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.