Minimum Number of Swaps to Make the Binary String Alternating - Problem
Given a binary string
You can swap any two characters in the string, regardless of their positions. If it's impossible to create an alternating pattern, return
For example,
s, your task is to transform it into an alternating pattern using the minimum number of character swaps. An alternating string has no two adjacent characters that are the same - think patterns like "010101" or "101010".You can swap any two characters in the string, regardless of their positions. If it's impossible to create an alternating pattern, return
-1.For example,
"110" can become "101" with just 1 swap, but "111" is impossible to make alternating since we need equal or near-equal counts of 0s and 1s. Input & Output
example_1.py โ Python
$
Input:
s = "111"
โบ
Output:
-1
๐ก Note:
It's impossible to make "111" alternating since we need both 0s and 1s. An alternating string requires roughly equal counts of each character.
example_2.py โ Python
$
Input:
s = "010"
โบ
Output:
0
๐ก Note:
The string "010" is already alternating (no adjacent characters are the same), so 0 swaps are needed.
example_3.py โ Python
$
Input:
s = "1110"
โบ
Output:
1
๐ก Note:
We can make "1110" alternating by swapping one character. For example, swap positions 1 and 3 to get "1010" or "0101" with 1 swap.
Constraints
- 1 โค s.length โค 105
- s[i] is either '0' or '1'
- The string contains only binary characters
Visualization
Tap to expand
Understanding the Visualization
1
Count Dancers
Count red and blue dancers (0s and 1s)
2
Check Feasibility
Verify counts differ by at most 1
3
Try Both Patterns
Test RBRBRB... and BRBRBR... arrangements
4
Calculate Swaps
Count misplaced dancers for each pattern
5
Choose Optimal
Pick the pattern requiring fewer moves
Key Takeaway
๐ฏ Key Insight: Only 2 possible alternating patterns exist! Count characters, verify feasibility, then test both patterns and choose the one requiring minimum swaps.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code