Ctrl K

Sliding Ones to the Right

Medium
You are given a string bits made of zeros and ones. In one move you pick a 1 that is immediately followed by a 0 and slide it to the right: it keeps going until it bumps into another 1 or reaches the end of the string. For example, moving the 1 at position 1 turns "0100101" into "0001101". Return the largest number of moves you can make if you choose their order well.
Example 1
bits='10100' → 3

Move the left 1 first: it slides up to its neighbour, "01100". Then the right one slides to the end, "01001". Then the left one again: "00011". That is 3 moves.

Example 2
bits='0011' → 0

No 1 is followed by a 0, so no move is possible.

Example 3
bits='1110' → 3

Move the third, then the second, then the first 1; each of them gets to move once.

Constraints
  • 1 ≤ len(bits) ≤ 10⁵
  • Every character of bits is '0' or '1'
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNo Twin Letters Side by Side MediumSplit Letters Into Palindromes MediumPalindrome From Two-Letter Cards MediumLargest String With a Run Cap MediumNine-Button Layout Medium
loading Python…
Input
bits='10100'
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 110 tests on the server, hidden ones included.