Problem Description
Given a binary string s, the goal is to return the minimum number of character swaps needed to make s alternating (i.e. no two adjacent characters are equal). A swap can be performed between any two positions. If it is impossible to form an alternating string, return -1.
Key Insights
- Only two alternating patterns are possible: one starting with '0' (e.g., "0101...") and one starting with '1' (e.g., "1010...").
- A valid alternating string imposes a constraint on the counts of '0's and '1's. For a string of even length, the counts must be equal; for an odd length, the difference must be exactly one.
- When comparing the given string to a candidate alternating pattern, each position that does not match represents a "misplaced" character.
- Since swapping any two misplaced characters will correct two positions at once, the number of swaps required is half the number of mismatches.
- For odd-length strings the valid candidate pattern is determined by the majority character.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, because we iterate over the string a constant number of times. Space Complexity: O(1), since only a few integer variables are used regardless of the input size.
Solution
The solution involves the following steps:
- Count the number of '0's and '1's in the string.
- Based on these counts, check if forming an alternating string is possible:
- For even-length strings, the counts must be equal.
- For odd-length strings, the difference between counts must be exactly one.
- Construct the two candidate alternating strings:
- One starting with '0' (i.e., "0101...")
- One starting with '1' (i.e., "1010...")
- For each candidate pattern, iterate through s and count the mismatches.
- Since each swap fixes two mismatches, the number of swaps is determined by dividing the mismatch count by 2.
- For even-length strings, return the minimum swaps from the two candidates.
- For odd-length strings, only the candidate that aligns with the majority element is valid.
Key data structures: simple integer counters and iterative loops. The trick is to realize a swap handles two mismatches simultaneously, so we can count only the positions that are off and then divide by two for the final answer.