Skip to content

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

Difficulty Topics

Description

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'.

Solution

minimum-number-of-swaps-to-make-the-binary-string-alternating.py
class Solution:
    def minSwaps(self, s: str) -> int:
        ones = zeroes = 0

        for c in s:
            if c == '0':
                zeroes += 1
            else:
                ones += 1

        if abs(zeroes - ones) > 1: return -1

        def countSwap(char):
            count = 0
            for c in s:
                if c != char:
                    count += 1
                char = '1' if char == '0' else '0'

            return count // 2

        if zeroes > ones:
            return countSwap('0')
        elif ones > zeroes:
            return countSwap('1')
        else:
            return min(countSwap('0'), countSwap('1'))