Talentd
FleetCode

1864. Minimum Number of Swaps to Make the Binary String Alternating

Medium44.1% acceptance2 companies

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:

Input: s = "111000"
Output: 1
Explanation: Swap positions 1 and 4: "111000" -> "101010"
The string is now alternating.

Example 2:

Input: s = "010"
Output: 0
Explanation: The string is already alternating, no swaps are needed.

Example 3:

Input: s = "1110"
Output: -1

Constraints:

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

Asked at 2 companies

Hints open one at a time

Hint 1
Think about all valid strings of length n.
Hint 2
Try to count the mismatched positions with each valid string of length n.
13:16
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def minSwaps(self, s: str) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"111000"
Input
"010"
Input
"1110"
Your code is saved on this device.Solution