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 — Basic Alternating Needed
$
Input:
s = "111"
›
Output:
-1
💡 Note:
Cannot make alternating: need equal count of 0s and 1s (±1), but have 3 ones and 0 zeros
Example 2 — One Swap Needed
$
Input:
s = "1110"
›
Output:
1
💡 Note:
Can swap to get "1010" (pattern starting with 1) or "0101" (pattern starting with 0). Pattern "1010" needs 1 swap: position 2 and 3
Example 3 — Already Alternating
$
Input:
s = "010"
›
Output:
0
💡 Note:
String is already alternating, no swaps needed
Constraints
- 1 ≤ s.length ≤ 1000
- s[i] is either '0' or '1'
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Count 0s and 1s, check if alternating possible
2
Pattern Matching
Compare against both possible alternating patterns
3
Optimal Swaps
Return minimum swaps needed
Key Takeaway
🎯 Key Insight: Only two alternating patterns exist - calculate swaps for each and pick minimum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code