Minimum Number of Swaps to Make the Binary String Alternating - Problem
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.
Input & Output
Example 1 — Equal 0s and 1s
$
Input:
s = "111"
›
Output:
1
💡 Note:
We can swap position 0 and 1 to get "111" → "111" is impossible. We need at least one '0'. Since we have 3 ones and 0 zeros, it's impossible to make alternating. Wait, let me recalculate: "111" has all 1s, we need to make it alternating. The only possible patterns are "010" or "101". For "010": need 2 swaps. For "101": need 2 swaps. But we can't swap to create 0s from 1s. Actually, this should return -1.
Example 2 — Already Alternating
$
Input:
s = "010"
›
Output:
0
💡 Note:
The string is already alternating, so no swaps needed
Example 3 — Need One Swap
$
Input:
s = "1110"
›
Output:
1
💡 Note:
We can swap one '1' with '0' to get "1010" which is alternating. One swap transforms "1110" to "1010"
Constraints
- 1 ≤ s.length ≤ 1000
- s[i] is either '0' or '1'
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code