Skip to the code
cf.
+10 XP

#556 Fewest Flips to Sort a Toggle Row

easy

A settings page shows a row of toggles as a string of 0 (off) and 1 (on). The design team wants every off toggle to come before every on toggle, like 000111, so they flip some toggles. A row of all off or all on toggles also counts.

Write fewestFlips(toggles) that returns the fewest toggles to flip.

Example 1

Input: toggles = "010110"
Output: 2

Flip positions 1 and 5 to get 000111.

Example 2

Input: toggles = "111"
Output: 0

All on already counts.

Constraints

  • 1 <= toggles.length <= 100000
  • toggles contains only 0 and 1.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).