Flip string to monotone increasing

January 17, 2023

array-and-hashmap

Problem URL: Flip string to monotone increasing

A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)

class Solution:
    def minFlipsMonoIncr(self, s: str) -> int:
        ones, res = 0, 0
        for num in s:
            if num == '1':
                ones += 1
            elif ones:
                ones -= 1
                res += 1
        return res

Time complexity: O(n), n is the length of the string.
Space complexity: O(1)