Problem 1769

Abstract / Summary

Given boxes with balls, for each box count moves needed to gather all balls into it based on ball positions.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
15 lines | 443 bytes | submitted November 27, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 90% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Prefix Sum
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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))
  • left counts how many balls have been seen to the left of the current position.
  • right holds the total number of balls that remain to the right of the current position, initially the total count of '1' characters.
  • have accumulates the total distance contributed by balls that are already on the left side.
  • need accumulates the total distance that would be contributed by balls on the right side if they were moved to the current index. The expression i if box == "1" else 0 adds 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 + need represents the sum of distances contributed by balls on both sides of the current index.
  • When a '1' is encountered, left is incremented because that ball now belongs to the left side for subsequent positions, and right is decremented because it is no longer part of the right side.
  • have += left adds the contribution of moving each ball on the left one step farther right as the index advances.
  • need -= right subtracts 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 have and need as cumulative distance contributions, the algorithm avoids recomputing distances for each index. The updates have += left and need -= right adjust 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) and need (sum of ball indices) uses generator expressions that run once before the main loop. This eliminates repeated counting inside the loop.

  • Generator Output - Using yield produces 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.63 | σ = 1.93

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
29 links | 16 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

10 solutions   November 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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