Minimum Number of Swaps to Make the Binary String Alternating Problem
Description
LeetCode Problem 1864.
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. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Any two characters may be swapped, even if they are not adjacent.
Example 1:
Input: s = "111000"
Output: 1
Explanation: Swap positions 1 and 4: "111000" -> "101010"
The string is now alternating.
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating, no swaps are needed.
Example 3:
Input: s = "1110"
Output: -1
Constraints:
1 <= s.length <= 1000s[i]is either'0'or'1'.
Solution
Approach: Counting Mismatches
Count the zeros and ones. An alternating string has equal counts, or one extra of the character it starts with. If the counts differ by more than 1, the answer is -1.
Otherwise, decide which target strings are possible:
- If one character is more frequent, the target must start with it.
- If the counts are equal, both targets (starting with
0or with1) are possible, and we take the cheaper one.
For one target, count the positions where s differs from it. A swap of two different characters repairs two mismatched positions at once, so the number of swaps is that count divided by 2.
Complexity: O(n) time and O(1) space.
class Solution:
def minSwaps(self, s: str) -> int:
def calc(c: int) -> int:
return sum((c ^ i & 1) != x for i, x in enumerate(map(int, s))) // 2
n0 = s.count("0")
n1 = len(s) - n0
if abs(n0 - n1) > 1:
return -1
if n0 == n1:
return min(calc(0), calc(1))
return calc(0 if n0 > n1 else 1)