Your Dashboard
Interview Coaching
Learn
System Design
ML System Design
Code
Behavioral
Salary Negotiation
Interview Guides
Leetcode 3228. Maximum Number of Operations to Move Ones to the End
Given a binary string s, you may repeatedly pick any adjacent "10" and slide that '1' rightward over all following zeros until it hits another '1' or the string end; compute the maximum number of such operations you can perform. The core challenge is to reason about the optimal order of moves and count movable ones efficiently (greedy/inversion-style scan over the string).
DESCRIPTION
Given a binary string s, you may repeatedly pick any adjacent "10" and slide that '1' rightward over all following zeros until it hits another '1' or the string end; compute the maximum number of such operations you can perform. The core challenge is to reason about the optimal order of moves and count movable ones efficiently (greedy/inversion-style scan over the string).
Input:
Output:
Explanation: First '1' at index 0 can slide over 1 zero (1 move). Second '1' at index 2 can slide over 2 zeros (2 moves). Total: 3 operations.
Constraints:
- 1 <= s.length <= 10^5
- s consists only of '0' and '1' characters
- Each operation slides a '1' over consecutive zeros until blocked
Understanding the Problem
Let's understand what we're being asked to do. We have a binary string like '10100' and can perform a specific operation: find any '10' substring and slide the '1' rightward over all following zeros until it hits another '1' or the end.
Tracing through '10100': We could pick the first '10' (positions 0-1) and slide the '1' right, transforming it to '01100'. Or we could pick the '10' at positions 2-3 and slide that '1' right to get '10010'. Each valid slide counts as one operation.
Important constraint: We can only slide a '1' that is immediately followed by a '0' (forming '10'). The '1' slides over consecutive zeros until blocked.
Edge cases to consider: What if the string has no '10' patterns? (no moves possible, return 0). What if all '1's are already at the right? What if we have '111000' (multiple ones can each slide)?
Brute Force Approach
The straightforward approach is to simulate the process: repeatedly scan the string for any '10' pattern, perform the slide operation (move the '1' rightward over zeros), increment the operation counter, and repeat until no more '10' patterns exist. This approach directly models the problem description but requires multiple passes through the string and string manipulation for each operation, making it inefficient for large inputs.
Start: Convert string to character array for manipulation
0 / 37
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n²) In the worst case (like '111...000...'), we perform O(n) operations, and each operation requires scanning and modifying the string which takes O(n) time, resulting in O(n²) total time
Space Complexity: O(n) We need O(n) space to store and manipulate the string during each operation
Building Intuition
Each '1' in the string can potentially slide rightward over zeros. The key insight is that a '1' at position i can slide over all zeros to its right until it hits another '1' or the end.
The order in which we perform slides matters! If we have '1010', sliding the first '1' blocks the second '1' from sliding as far.
By thinking about each '1' independently and counting how many positions it can slide, we can compute the total number of operations.
The crucial realization: processing '1's from right to left (or tracking how many zeros are available) lets us count moves without simulating each step. Each '1' can slide over all zeros to its right that aren't already "claimed" by '1's further right.
Imagine cars (ones) on a highway with empty spaces (zeros) ahead. Each car wants to move forward into empty spaces.
If we process cars from back to front, each car can count exactly how many empty spaces it can claim. The first car (rightmost '1') claims all zeros to its right. The second car claims zeros between it and the first car, and so on.
This is like counting inversions - how many zeros does each '1' need to "jump over" to reach its final position?
Common Mistakes
Optimal Solution
The optimal approach scans the string from right to left, tracking how many zeros we've seen so far. Each time we encounter a '1', it can slide over all the zeros to its right (the count we've been tracking), and we add this count to our total operations. After counting a '1''s contribution, we increment the zero count (because this '1' will act as a zero-space for '1's further left after it slides). This greedy single-pass approach counts all possible operations without simulation.
Start: Count maximum slide operations for binary string
0 / 19
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n) We make a single pass through the string, examining each character once, resulting in linear time complexity
Space Complexity: O(1) We only need a constant amount of extra space to track the count of zeros and total operations
What We've Learned
- Greedy right-to-left scanning: When elements need to move to the end based on relative positions, scan from right to left to count how many positions each element can move - this naturally accumulates the total operations because later '1's block earlier ones, making a single pass sufficient.
- Inversion counting pattern: This problem is fundamentally about counting inversions (how many '0's each '1' must pass over) - recognize that 'moving elements to the end' problems often reduce to counting how many obstacles each element encounters, summed across all movable elements.
- Cumulative zero tracking: Maintain a running count of zeros encountered so far (scanning right-to-left) - when you hit a '1', add the zero count to your result because that '1' can slide over all those zeros, then increment the zero count to account for this '1' becoming an obstacle for future '1's.
- Order independence insight: The key realization is that the total number of operations is independent of the order you perform them - each '1' will eventually move past all '0's to its right, so you can simply count all possible moves rather than simulating the actual movement sequence.
- Single-pass O(n) optimization: Avoid simulating the actual string modifications (which would be O(n²) or worse) - instead, recognize that you can compute the answer analytically by counting relationships between '1's and '0's in one linear scan, trading simulation for mathematical reasoning.
- Relative positioning problems: Apply this counting approach to any problem where elements move based on relative order constraints (bubble sort operations, minimum swaps, array rearrangement) - often the total operations needed equals the sum of 'distances' each element must travel past blocking elements.
Related Concepts and Problems to Practice
easy
This problem involves moving elements (zeroes) to the end of an array while maintaining relative order, which is conceptually similar to moving ones to the end. Both require understanding of in-place array manipulation and optimal ordering of operations.
medium
This problem requires partitioning elements in an array by moving them to specific positions, similar to the greedy approach needed for moving ones. It teaches efficient single-pass algorithms for rearranging array elements based on their values.
The original problem requires greedy reasoning to determine the optimal order of operations and count moves efficiently. This lesson provides foundational understanding of greedy strategies that apply to problems involving optimal sequencing and counting operations.
Test Your Understanding
Why is array the right data structure for this problem?
array provides the optimal access pattern
It's the only data structure that works
It's the easiest to implement
It uses the least memory
Select an answer to see the explanation
Question Timeline
See when this question was last asked and where, including any notes left by other candidates.
Comments
Hello Interview Premium
Your account is free and you can post anonymously if you choose.