Problem Description
Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal.
Key Insights
- An alternating string will have an equal number of '0's and '1's or differ by one.
- If the absolute difference between the number of '0's and '1's is greater than 1, it is impossible to form an alternating string.
- The minimum swaps needed can be derived from the mismatched positions of '0's and '1's in the string compared to the desired alternating pattern.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We will count the number of '0's and '1's in the given binary string. If the difference in their counts is greater than one, return -1. Otherwise, we will compute the number of mismatches against two possible alternating patterns: starting with '0' and starting with '1'. The minimum number of swaps required will be half the number of mismatches since each swap fixes two positions.