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
iwherei + 1 < s.length - The character at position
imust be'1'and at positioni + 1must 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code