Minimum Number of Flips to Make the Binary String Alternating — LeetCode 1888 Python Solution

MediumStringDynamic ProgrammingSliding Window
Problem
#1888
Reading time
2 min

The problem

You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string.

Example

Input
s = "111000"
Output
2
Explanation
Use the first operation two times to make s = "100011".

Python solution

Python
class Solution:
    def minFlips(self, s: str) -> int:
        n = len(s)
        target = "01"
        cnt = sum(c != target[i & 1] for i, c in enumerate(s))
        ans = min(cnt, n - cnt)
        for i in range(n):
            cnt -= s[i] != target[i & 1]
            cnt += s[i] != target[(i + n) & 1]
            ans = min(ans, cnt, n - cnt)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1888. Minimum Number of Flips to Make the Binary String Alternating is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1888. Minimum Number of Flips to Make the Binary String Alternating?
LeetCode 1888. Minimum Number of Flips to Make the Binary String Alternating is rated Medium on LeetCode.
What topics does LeetCode 1888. Minimum Number of Flips to Make the Binary String Alternating cover?
LeetCode 1888. Minimum Number of Flips to Make the Binary String Alternating is tagged String, Dynamic Programming and Sliding Window 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