Flip String to Monotone Increasing

A binary string is monotone increasing if it is some number of '0's (possibly none) followed by some number of '1's (possibly none). Given a binary string s, you may flip any character from '0' to '1' or from '1' to '0'. Return the minimum number of flips that makes s monotone increasing.

30:00

Flip String to Monotone Increasing
medium
Free written solution
Topics
Companies

A binary string is monotone increasing if it is some number of '0's (possibly none) followed by some number of '1's (possibly none). Given a binary string s, you may flip any character from '0' to '1' or from '1' to '0'. Return the minimum number of flips that makes s monotone increasing.

Example 1:
Input: {"s":"00110"}
Output: 1
Constraints:
  • 1≤s.length≤1051 \leq s.\text{length} \leq 10^5

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

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"00110"}

Scan s (length 5) once. ones counts the '1's seen; flips is the fewest flips that make the prefix monotone.

s and the cheapest target for s[0..0]: zeros left of the cut, ones right of it

s

0
0
1
1
0

target

0

1

2

3

4

cut

kept

flipped

current

whole string: scanned part and where the best cut sits

05

ones = 0

cut = 0

flips = 0

Variables
VariableValue
i-1
ones0
flips0
DepthFunction Call
Stack empty
0/7