Flip String to Monotone Increasing (LeetCode 926): Solution and Explanation

Medium
String
Dynamic Programming

Given a binary string s, find the fewest character flips that turn it into some zeros followed by some ones. For "00110" one flip is enough: change the last 0 to get "00111".

Intuition

Any monotone string is a wall: every position left of some cut is 0 and every position right of it is 1. For a fixed cut the cost is the ones before it plus the zeros after it.

You could try all n + 1 cuts with prefix counts, but one pass can keep the answer for every prefix as it grows.

Suppose flips is the best cost for the prefix so far and ones counts its ones. Appending a 1 costs nothing, because a 1 can always sit right of the cut.

Appending a 0 leaves two choices. Flip it to 1 and keep the old cut, costing flips + 1. Or move the cut past it so the whole prefix becomes zeros, which means flipping every earlier one, costing ones. The new best is the smaller of the two.

Approach: One-pass DP

  1. Set ones = 0 and flips = 0.
  2. For each character: if it is '1', add 1 to ones.
  3. Otherwise set flips = min(flips + 1, ones).
  4. Return flips.

Step-by-step example

s = "010110"
  1. Index 0 is 0: min(0 + 1, 0) = 0, so flips stays 0 with the cut after it.
  2. Index 1 is 1: ones = 1.
  3. Index 2 is 0: min(0 + 1, 1) = 1. Either choice costs 1.
  4. Indices 3 and 4 are 1: ones = 3.
  5. Index 5 is 0: min(1 + 1, 3) = 2, so flip this last zero. The answer is 2.

Code: Python, Java, C++

1class Solution:
2    def minFlipsMonoIncr(self, s: str) -> int:
3        ones = 0
4        flips = 0
5        for ch in s:
6            if ch == '1':
7                ones += 1
8            else:
9                flips = min(flips + 1, ones)
10        return flips
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is looked at once with constant work.

Space

O(1)

Only the two counters ones and flips are stored.

Other approaches

Prefix ones and suffix zeros (time O(n), space O(n))

Count the ones before each cut and the zeros after it, then take the minimum of their sum over all n + 1 cuts. Easy to reason about but needs extra arrays.

Two-state DP (time O(n), space O(1))

Track the cost of a prefix that ends in 0 and one that ends in 1. The one-pass method above is the same DP with the ends-in-0 state folded into the ones counter.

Common mistakes

  • Flipping only zeros or only ones. The best answer usually mixes both, as in "010110" where neither pure choice gives 2.
  • Using flips + 1 and ones the wrong way round. A 0 either becomes a 1 (one more flip) or forces all earlier ones to become zeros.
  • Updating flips on a 1. A trailing one never adds cost; only ones changes.
  • Forgetting the cut may sit at either end. An all-ones or all-zeros target is allowed, which the min already covers.

Frequently asked questions

Why can a '1' be appended for free?

Whatever the best monotone target for the prefix was, putting a 1 after it keeps it monotone. So the cost of the prefix does not change.

Why is the cost of making the prefix all zeros equal to ones?

Turning the prefix into all zeros means flipping exactly the ones in it, and ones counts them.

Is this the same as Minimum Deletions to Make String Balanced?

It is the same idea with a b in place of a 1. There you delete characters instead of flipping them, but the cost recurrence is identical.