Minimum Suffix Flips — LeetCode 1529 Python Solution

MediumGreedyString
Problem
#1529
Pattern
Greedy
Reading time
2 min

The problem

You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros.

Example

Input
target = "10111"
Output
3
Explanation
Initially, s = "00000".

Python solution

Python
class Solution:
    def minFlips(self, target: str) -> int:
        ans = 0
        for v in target:
            if (ans & 1) ^ int(v):
                ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1529. Minimum Suffix Flips 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 1529. Minimum Suffix Flips?
LeetCode 1529. Minimum Suffix Flips is rated Medium on LeetCode.
What is the time complexity of LeetCode 1529. Minimum Suffix Flips?
The Python solution on this page runs in O(n), where n is the length of the string.
What is the space complexity of LeetCode 1529. Minimum Suffix Flips?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1529. Minimum Suffix Flips cover?
LeetCode 1529. Minimum Suffix Flips 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