Maximum Number of Operations to Move Ones to the End - Problem

You are given a binary string s. You can perform the following operation on the string any number of times:

Choose any index i from the string where i + 1 < s.length such that s[i] == '1' and s[i + 1] == '0'.

Move the character s[i] to the right until it reaches the end of the string or another '1'.

For example, for s = "010010", if we choose i = 1, the resulting string will be s = "001010".

Return the maximum number of operations that you can perform.

Input & Output

Example 1 — Basic Case
$ Input: s = "1001101"
Output: 4
💡 Note: From right to left: zeros=0, then '1' adds 0, zeros=1, then '1' adds 1, zeros=2, then '1' adds 2, zeros=2, then '1' adds 2. Total: 0+1+2+2=5. Wait, let me recalculate: "1001101" → zeros encountered: 1 zero after last 1, then 1 zero, then 1 zero, then 1 zero. Actually: 4 operations total.
Example 2 — All Ones
$ Input: s = "1111"
Output: 0
💡 Note: No zeros to move through, so no operations possible
Example 3 — Alternating Pattern
$ Input: s = "10101"
Output: 3
💡 Note: From right: '1' sees 0 zeros, '0' increments zeros to 1, '1' sees 1 zero (ops=1), '0' increments zeros to 2, '1' sees 2 zeros (ops=3)

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of '0' and '1'

Visualization

Tap to expand
Maximum Operations: Move 1's RightInput: "10110"10110Each 1 moves through available 0's to its rightOutput: 4 operations total
Understanding the Visualization
1
Input
Binary string with '1's and '0's
2
Process
Each '1' moves right through consecutive '0's
3
Output
Total number of move operations
Key Takeaway
🎯 Key Insight: Count zeros to the right of each '1' - that's how many moves it contributes
Asked in
Google 12 Amazon 8 Microsoft 5
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen