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
INPUTALGORITHMRESULT"1110"Count: 3 ones, 1 zeroDifference = 2, but ≤ 1 neededActually |3-1| = 2 > 11Check if possible2Try pattern "0101"3Try pattern "1010"4Return minimum-1ImpossibleCannot make alternatingToo many 1s vs 0sKey Insight:Only two alternating patterns exist. Check if |count0 - count1| ≤ 1,then compare with both patterns and return minimum swaps needed.TutorialsPoint - Minimum Swaps Binary Alternating | Greedy Pattern Matching
Asked in
Google 15 Facebook 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
847 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