Flip String to Monotone Increasing

MediumDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A binary string is **monotone increasing** if it is some number of '0's followed by some number of '1's (either part may be empty). Given a binary string s, you may flip any character ('0' to '1' or '1' to '0'). Return the minimum number of flips that makes s monotone increasing. Aim for O(n) time.

Examples

Input: s = "00110"
Output: 1
Flip the last character to get "00111".
Input: s = "010110"
Output: 2
Flip to get "011111" (or "000111").
Input: s = "00011000"
Output: 2
Flip the two 1s to get "00000000".

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is '0' or '1'

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems