Minimum Number of Swaps to Make the Binary String Alternating — LeetCode 1864 Python Solution

MediumGreedyString
Problem
#1864
Pattern
Greedy
Reading time
2 min

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

Example

Input
s = "111000"
Output
1
Explanation
Swap positions 1 and 4: "111000" -> "101010"

Python solution

Python
class Solution:
    def minSwaps(self, s: str) -> int:
        def calc(c: int) -> int:
            return sum((c ^ i & 1) != x for i, x in enumerate(map(int, s))) // 2

        n0 = s.count("0")
        n1 = len(s) - n0
        if abs(n0 - n1) > 1:
            return -1
        if n0 == n1:
            return min(calc(0), calc(1))
        return calc(0 if n0 > n1 else 1)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string \textit{s}
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating?
LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating is rated Medium on LeetCode.
What is the time complexity of LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating?
The Python solution on this page runs in O(n), where n is the length of the string \textit{s}.
What is the space complexity of LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating cover?
LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating is tagged Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview