MediumNo. 1864

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

Pattern
Greedy
Topics
Greedy, String
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

PythonSolution
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

Time
O(n)where n is the length of the string s
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0316Remove Duplicate LettersMedium
0402Remove K DigitsMedium
0420Strong Password CheckerHard
0649Dota2 SenateMedium
0680Valid Palindrome IIEasy

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.

Free to download. Check it runs on your machine, then pick a plan.