Flip String to Monotone Increasing (LeetCode 926): Solution and Explanation
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
- Set
ones = 0andflips = 0. - For each character: if it is
'1', add 1 toones. - Otherwise set
flips = min(flips + 1, ones). - Return
flips.
Step-by-step example
s = "010110"
- Index 0 is
0:min(0 + 1, 0) = 0, so flips stays 0 with the cut after it. - Index 1 is
1: ones = 1. - Index 2 is
0:min(0 + 1, 1) = 1. Either choice costs 1. - Indices 3 and 4 are
1: ones = 3. - 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 flips1class Solution {
2 public int minFlipsMonoIncr(String s) {
3 int ones = 0, flips = 0;
4 for (char ch : s.toCharArray()) {
5 if (ch == '1') {
6 ones++;
7 } else {
8 flips = Math.min(flips + 1, ones);
9 }
10 }
11 return flips;
12 }
13}1class Solution {
2public:
3 int minFlipsMonoIncr(string s) {
4 int ones = 0, flips = 0;
5 for (char ch : s) {
6 if (ch == '1') {
7 ones++;
8 } else {
9 flips = min(flips + 1, ones);
10 }
11 }
12 return flips;
13 }
14};Time and space complexity
O(n)
Each character is looked at once with constant work.
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 + 1andonesthe wrong way round. A0either becomes a1(one more flip) or forces all earlier ones to become zeros. - Updating
flipson a1. A trailing one never adds cost; onlyoneschanges. - 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.