All problems
1029MediumStringDynamic Programming

Fewest Switch Throws to Settle the Row

Tracked in this browser only
Write code

Trains the technique from

LeetCode 926Flip String to Monotone Increasing

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A row of switches reads row, each character '0' for down and '1' for up. One throw changes a single switch, either way.

The row is settled when no switch that is down comes after a switch that is up: all the downs first, then all the ups, and either group may be empty.

Return the fewest throws that settle the row.

Examples

Example 1

Input
row = "111000"
Output
3

Three ups then three downs. Throwing all three ups down settles the row, and so does throwing all three downs up, either way three throws. Nothing shorter works, since every up sits before every down.

Example 2

Input
row = "0000"
Output
0

Every switch is down, which is already settled.

Example 3

Input
row = "10"
Output
1

One up followed by one down. A single throw on either switch settles it.

Constraints

  • 1 <= row.length <= 10^5
  • Every character of row is '0' or '1'.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def min_flips_mono_incr(row: str) -> int:
Java
public int minFlipsMonoIncr(String row)
September 7
Apply