Mid/SeniorGreedyString

Minimum Number of Swaps to Make the Binary String Alternating

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.

Example 1
Inputs = "111000"
Output1
Swap positions 1 and 4 to transform "111000" into "101010", which is alternating.
Example 2
Inputs = "010"
Output0
The string is already alternating, so no swaps are needed.

Constraints

  • 1 <= s.length <= 1000
  • s[i] is either '0' or '1'.

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate