Python 1769.py
class Solution:
def minOperations(self, boxes: str) -> List[int]:
left = 0
right = sum(int(c) for c in boxes)
have = 0
need = sum(i if box == "1" else 0 for i, box in enumerate(boxes))
for i, box in enumerate(boxes):
yield have + need
if box == "1":
left += 1
right -= 1
have += left
need -= right
Difficulty
and has an acceptance rate of about 90% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Prefix Sum
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution.minOperations method computes, for each position in a binary string boxes, the total number of moves required to bring all balls (represented by '1') to that position. The implementation returns a generator that yields the result for each index in order, allowing the caller to consume the values lazily. The algorithm proceeds in a single linear scan, maintaining running counters that reflect the state of the left and right sides of the current index.
Key Steps
Initial Counters
The method begins by establishing three aggregates that describe the distribution of balls relative to the current index.
left = 0
right = sum(int(c) for c in boxes)
have = 0
need = sum(i if box == "1" else 0 for i, box in enumerate(boxes))
leftcounts how many balls have been seen to the left of the current position.rightholds the total number of balls that remain to the right of the current position, initially the total count of'1'characters.haveaccumulates the total distance contributed by balls that are already on the left side.needaccumulates the total distance that would be contributed by balls on the right side if they were moved to the current index. The expressioni if box == "1" else 0adds the index of each ball, which represents its distance to position zero.
These pre-computed sums enable the algorithm to update the answer for each index in constant time.
Main Loop and Yield
The core of the method iterates over the string, yielding the current total number of moves and then updating the counters based on the character at the current index.
for i, box in enumerate(boxes):
yield have + need
if box == "1":
left += 1
right -= 1
have += left
need -= right
- The expression
have + needrepresents the sum of distances contributed by balls on both sides of the current index. - When a
'1'is encountered,leftis incremented because that ball now belongs to the left side for subsequent positions, andrightis decremented because it is no longer part of the right side. have += leftadds the contribution of moving each ball on the left one step farther right as the index advances.need -= rightsubtracts the contribution of moving each ball on the right one step closer left as the index advances.
Because the loop updates the aggregates incrementally, each iteration performs only a few arithmetic operations, avoiding any recomputation of distances from scratch.
Edge Cases Handled
The algorithm gracefully handles an empty input string. In that scenario, the initial sums evaluate to zero, the for loop does not execute, and the generator yields no values, which is the correct behavior for a problem with no positions.
When the string consists entirely of '0' characters, right and need start at zero, and left and have remain zero throughout the scan. The yielded values are all zero, reflecting that no moves are required because there are no balls to relocate.
If the string is composed solely of '1' characters, right initially equals the length of the string, and need equals the sum of all indices. As the loop progresses, left grows from zero to the full count, while right shrinks to zero. The incremental updates correctly adjust have and need so that each yielded value corresponds to the total distance needed to gather all balls at the current index.
A single-character string, either '0' or '1', is also covered. For '0', the generator yields a single zero. For '1', the initial right is one, need is zero, and after the first (and only) iteration the yielded value is zero, indicating that the ball is already at its own position.
Performance Optimizations
The implementation achieves high efficiency through several deliberate choices:
-
Single Pass - All required information is derived in one traversal of the input. No nested loops or secondary passes are introduced, which keeps the total work proportional to the length of the string.
-
Incremental Updates - By maintaining
haveandneedas cumulative distance contributions, the algorithm avoids recomputing distances for each index. The updateshave += leftandneed -= rightadjust the totals in constant time as the window slides one step to the right. -
Pre-computed Totals - The initial calculation of
right(total ball count) andneed(sum of ball indices) uses generator expressions that run once before the main loop. This eliminates repeated counting inside the loop. -
Generator Output - Using
yieldproduces results lazily. Consumers that only need a subset of the answers can stop iteration early, saving the cost of processing the remainder of the string. -
Minimal Data Structures - The method relies only on a few integer variables and does not allocate auxiliary arrays or lists, reducing memory pressure and improving cache locality.
These design decisions collectively ensure that the function runs quickly even for very long input strings while keeping memory usage low.
ELI5 - Simplified Explanation
Imagine a long row of little toy boxes sitting on a shelf. Some of these boxes have a shiny marble inside them, and some are empty. There is a clever piece of code that wants to figure out exactly how many steps it would take to move every single marble to one specific box.
The code looks at each box one by one. It keeps track of how many marbles are on the left side and how many marbles are on the right side. By knowing where all the marbles are hiding, it calculates how much work is needed to bring them all together into the current box being looked at.
First, the code counts all the marbles to know the total. Then it starts walking down the line. As it moves from one box to the next, it updates its count. If the code sees a marble in the box it is currently standing at, it knows that the number of steps to move everything will change slightly for the next box. By adding up the steps for the marbles on the left and the marbles on the right, it finds the answer for every single spot on the shelf. This way, nothing gets left behind and all the marbles can gather in one place efficiently.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Java | |||||||||
| leetcode.ca | C++ | Python | JS | Java | C | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| wisdompeak | C++ | ||||||||||
| withaarzoo | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| wisdompeak | C++ | ||||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 1217: Minimum Cost to Move Chips to The Same Position
- problem 2459: Sort Array by Moving Items to Empty Space
- problem 2850: Minimum Moves to Spread Stones Over Grid
Solved On The Same Day
- problem 1005: Maximize Sum Of Array After K Negations
- problem 935: Knight Dialer
- problem 1029: Two City Scheduling
- problem 2080: Range Frequency Queries
- problem 793: Preimage Size of Factorial Zeroes Function
- problem 878: Nth Magical Number
- problem 902: Numbers At Most N Given Digit Set
- problem 1751: Maximum Number of Events That Can Be Attended II
- problem 1793: Maximum Score of a Good Subarray
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality