MediumNo. 0926

Flip String to Monotone Increasing — LeetCode 926 Python Solution

Topics
String, Dynamic Programming
Reading time
2 min

The problem

A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none). You are given a binary string s.

Example

Input
s = "00110"
Output
1
Explanation
We flip the last digit to get 00111.

Python solution

PythonSolution
class Solution:
    def minFlipsMonoIncr(self, s: str) -> int:
        tot = s.count("0")
        ans, cur = tot, 0
        for i, c in enumerate(s, 1):
            cur += int(c == "0")
            ans = min(ans, i - cur + tot - cur)
        return ans

Complexity

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

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 926. Flip String to Monotone Increasing is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard
0072Edit DistanceMedium
0087Scramble StringHard

Frequently asked questions

How hard is LeetCode 926. Flip String to Monotone Increasing?

LeetCode 926. Flip String to Monotone Increasing is rated Medium on LeetCode.

What is the time complexity of LeetCode 926. Flip String to Monotone Increasing?

The Python solution on this page runs in O(n), where n is the length of the string s.

What is the space complexity of LeetCode 926. Flip String to Monotone Increasing?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 926. Flip String to Monotone Increasing cover?

LeetCode 926. Flip String to Monotone Increasing is tagged String and Dynamic Programming 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.