Minimum Number of Swaps to Make the Binary String Alternating - Problem
Given a binary string 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
Alternating Pattern StrategyInput: "1110"1110Count: 3ร—'1', 1ร—'0'|3-1| = 2 > 1? โŒNeed more 0s!Corrected: "11100"11100Count: 3ร—'1', 2ร—'0'|3-2| = 1 โ‰ค 1? โœ…Alternating possible!Pattern 1: Start with '1'1โ†’11โ†’01โ†’10โ†’00โ†’1Target: 10101, Mismatches: 2, Swaps: 1Pattern 2: Start with '0'1โ†’01โ†’11โ†’00โ†’10โ†’0Target: 01010, Mismatches: 4, Swaps: 2๐ŸŽฏ Answer: min(1, 2) = 1
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
41.3K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen