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 IncreasingInput:10011Not monotone: 1s appear before 0sOutput:000111 flip neededMonotone increasing: all 0s before all 1s
Understanding the Visualization
1
Input String
Binary string "10011" that needs to be monotone
2
Find Optimal Split
Determine best position to separate 0s and 1s
3
Monotone Result
Flip minimum characters to achieve 0s followed by 1s
Key Takeaway
🎯 Key Insight: At each '0', choose between flipping it to '1' or flipping all previous '1's to '0's - take the minimum cost option.
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