Leetcode Problem 1864. Minimum Number of Swaps to Make the Binary String Alternating
1864. Minimum Number of Swaps to Make the Binary String Alternating
Leetcode Solutions
Counting Swaps for Alternating Binary String
Count the number of '0's and '1's in the string.
If the absolute difference between the counts is greater than 1, return -1.
If the counts are equal, calculate the number of swaps needed to alternate starting with '0' and starting with '1', and return the minimum of the two.
If the counts are not equal, calculate the number of swaps needed based on which character is in excess.
To calculate the number of swaps, iterate through the string and count the number of characters that are out of place for the expected alternating pattern.
The number of swaps is half the number of characters out of place since each swap corrects two positions.