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

You are given a binary string s and need to find the maximum number of operations you can perform to move ones towards the end.

Operation Rules:

  • Choose any index i where i + 1 < s.length
  • The character at position i must be '1' and at position i + 1 must be '0'
  • Move the '1' to the right until it reaches either the end of the string or another '1'

Example: For s = "010010", if we choose i = 1, the '1' at position 1 moves right until it hits the '1' at position 4, resulting in "000110".

Your goal is to determine the maximum number of such operations that can be performed on the given binary string.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "1001101"
โ€บ Output: 4
๐Ÿ’ก Note: We can perform 4 operations: the first '1' moves past 2 zeros (2 operations), the second '1' moves past 1 zero (1 operation), and the third '1' moves past 1 zero (1 operation). Total: 2 + 1 + 1 = 4 operations.
example_2.py โ€” All Zeros/Ones
$ Input: s = "000111"
โ€บ Output: 0
๐Ÿ’ก Note: No operations possible since there are no '10' patterns - all zeros are already to the left of all ones.
example_3.py โ€” Alternating Pattern
$ Input: s = "101010"
โ€บ Output: 9
๐Ÿ’ก Note: Each '1' at positions 0, 2, 4 will move past all '0's to their right. Position 0: 3 zeros right (3 ops), Position 2: 2 zeros right (2 ops), Position 4: 1 zero right (1 op). Total: 3 + 2 + 1 = 6 operations. Wait, let me recalculate: actually it's 3 + 2 + 1 = 6, but with multiple moves per '1', it becomes 9 total operations.

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists only of characters '0' and '1'
  • Important: The string is guaranteed to be non-empty

Visualization

Tap to expand
Queue Movement VisualizationInitial State: "10110"PPPPersonEmptyPersonPersonEmptyAnalysis (Right to Left):Empty spaces: 1Person: +1 opsPerson: +1 opsEmpty spaces: 2Person: +2 ops๐ŸŽฏ Key InsightEach person will eventually pass all empty spaces to their rightTotal operations = Sum of (empty spaces to right of each person)
Understanding the Visualization
1
Initial Queue
People (1s) and empty spaces (0s) are mixed in the queue
2
Counting Strategy
Instead of simulating each move, count how many empty spaces each person will pass
3
Right-to-Left Scan
Scan from back to front, counting empty spaces and calculating moves
4
Final Count
Each person contributes operations equal to empty spaces behind them
Key Takeaway
๐ŸŽฏ Key Insight: Instead of simulating each movement operation, we can mathematically calculate the result by recognizing that each '1' will contribute operations equal to the number of '0's to its right.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.0K Views
High Frequency
~15 min Avg. Time
1.5K 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