Flip String to Monotone Increasing - 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. You can flip s[i] changing it from 0 to 1 or from 1 to 0.

Return the minimum number of flips to make s monotone increasing.

Input & Output

Example 1 — Basic Case
$ Input: s = "10011"
Output: 1
💡 Note: We can flip s[1] = '0' to get "11011", then flip s[2] = '0' to get "11111". Total: 2 flips. Or we can flip s[0] = '1' to get "00011" which is monotone increasing. Total: 1 flip (optimal).
Example 2 — Already Monotone
$ Input: s = "00111"
Output: 0
💡 Note: String is already monotone increasing (0s followed by 1s), so no flips needed.
Example 3 — All Same Characters
$ Input: s = "1111"
Output: 0
💡 Note: All 1s is monotone increasing, so no flips needed.

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either '0' or '1'

Visualization

Tap to expand
Flip String to Monotone Increasing INPUT Binary String s: 1 idx 0 0 idx 1 0 idx 2 1 idx 3 1 idx 4 Goal: Make string monotone increasing (0s then 1s) Valid patterns: "00011", "00111", "01111" Input: s = "10011" Issue: '1' at idx 0 before '0's ALGORITHM STEPS 1 Track ones_count Count 1s seen so far 2 Track flips needed Min flips to make monotone 3 For each char: If '1': ones_count++ 4 If '0': flips = min(flips+1, ones) Trace through "10011": idx char ones flips action 0 1 1 0 ones++ 1 0 1 1 min(1,1) 2 0 1 1 min(2,1) 3 1 2 1 ones++ 4 1 3 1 ones++ FINAL RESULT Original: "10011" 1 0 0 1 1 FLIP After 1 flip: "00011" 0 0 0 1 1 Monotone increasing: OK (all 0s before all 1s) Output: 1 Key Insight: At each position, we have two choices: flip all previous 1s to 0s OR flip current 0 to 1. The DP approach tracks min(flip_current_0, flip_all_previous_1s) giving O(n) time, O(1) space. TutorialsPoint - Flip String to Monotone Increasing | Optimal DP Solution
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
87.0K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen