Minimum Number of Operations to Move All Balls to Each Box (LeetCode 1769): Solution and Explanation
A binary string marks which boxes in a row hold a ball. Moving one ball to a neighboring box costs one operation. For every box, return how many operations it would take to gather all the balls into that box, starting each time from the original layout.
Intuition
A ball at position j needs |i - j| moves to reach box i, so answer[i] is just the sum of distances from i to every ball. Computing that directly for every box is O(n²), which works for n = 2000 but repeats a lot of arithmetic.
Split each sum into two halves: balls sitting to the left of i and balls sitting to the right. Look at the left half first. When the target moves from box i to box i + 1, every ball on the left gets exactly one step farther away. So the left cost grows by the number of left balls, nothing else.
That turns the left half into a running total. Walk from left to right with two counters: balls, how many balls you have passed, and moves, what it costs to bring all of them to the current box. At each box, record moves, pick up the ball if there is one, then add balls to moves for the step to the next box.
The right half is the mirror image, so a second sweep from the right end with the counters reset adds the remaining cost. Two linear passes give every answer.
Approach: Two sweeps with running cost
- Create
answerof length n filled with zeros, and setballs = 0,moves = 0. - For i from 0 to n - 1: add
movestoanswer[i], add 1 toballsifboxes[i]is '1', then addballstomoves. - Reset
ballsandmovesto 0. - For i from n - 1 down to 0: repeat the same three updates, which adds the cost of the balls to the right.
- Return
answer.
Step-by-step example
boxes = "110"
- Left sweep, i = 0:
answer[0] += 0. Box 0 has a ball, soballs= 1 andmoves= 1. - i = 1:
answer[1] += 1. Box 1 has a ball, soballs= 2 andmoves= 3. - i = 2:
answer[2] += 3. Box 2 is empty,ballsstays 2 andmoves= 5. After the left sweepansweris [0,1,3]. - Right sweep, i = 2:
answer[2] += 0. Box 2 is empty, somovesstays 0. - i = 1:
answer[1] += 0. Box 1 has a ball, soballs= 1 andmoves= 1. - i = 0:
answer[0] += 1. The final answer is [1,1,3].
Code: Python, Java, C++
1class Solution:
2 def minOperations(self, boxes: str) -> List[int]:
3 n = len(boxes)
4 answer = [0] * n
5 balls = 0
6 moves = 0
7 for i in range(n):
8 answer[i] += moves
9 balls += int(boxes[i])
10 moves += balls
11 balls = 0
12 moves = 0
13 for i in range(n - 1, -1, -1):
14 answer[i] += moves
15 balls += int(boxes[i])
16 moves += balls
17 return answer1class Solution {
2 public int[] minOperations(String boxes) {
3 int n = boxes.length();
4 int[] answer = new int[n];
5 int balls = 0;
6 int moves = 0;
7 for (int i = 0; i < n; i++) {
8 answer[i] += moves;
9 balls += boxes.charAt(i) - '0';
10 moves += balls;
11 }
12 balls = 0;
13 moves = 0;
14 for (int i = n - 1; i >= 0; i--) {
15 answer[i] += moves;
16 balls += boxes.charAt(i) - '0';
17 moves += balls;
18 }
19 return answer;
20 }
21}1class Solution {
2public:
3 vector<int> minOperations(string boxes) {
4 int n = boxes.size();
5 vector<int> answer(n, 0);
6 int balls = 0;
7 int moves = 0;
8 for (int i = 0; i < n; i++) {
9 answer[i] += moves;
10 balls += boxes[i] - '0';
11 moves += balls;
12 }
13 balls = 0;
14 moves = 0;
15 for (int i = n - 1; i >= 0; i--) {
16 answer[i] += moves;
17 balls += boxes[i] - '0';
18 moves += balls;
19 }
20 return answer;
21 }
22};Time and space complexity
O(n)
Each sweep visits every box once and does constant work there.
O(1)
Apart from the output array, only the two counters are stored.
Other approaches
Sum distances for every box (time O(n²), space O(1))
For each box i, loop over all boxes j that hold a ball and add |i - j|. It is short and easy to trust, and n = 2000 keeps it under the time limit, but it does n times more work than needed.
Prefix counts and prefix position sums (time O(n), space O(n))
Store prefix counts of balls and prefix sums of their indices. The left cost for box i is i * countLeft - sumLeft and the right cost is sumRight - i * countRight. It answers any single box in O(1) after O(n) setup.
Common mistakes
- Updating
movesbefore adding it toanswer[i]. The cost recorded for box i must not include the step to i + 1. - Forgetting to reset
ballsandmovesbetween the two sweeps, which counts the left-side balls a second time. - Adding the ball in box i to its own cost. A ball already in the target box needs zero moves, which the order of updates handles naturally.
- Reading
boxes[i]as a character and adding it directly in a language where '1' is 49, instead of converting it to 0 or 1.
Frequently asked questions
Why does moves grow by balls at each step?
Every ball already passed is one box farther from the next target than from the current one. With balls of them, the total cost goes up by exactly balls.
Does the order of moving balls matter?
No. Each ball travels independently and the cheapest path for one ball is a straight walk of |i - j| steps, so the answer is the plain sum of distances.
Is the brute force fast enough here?
With n up to 2000 the O(n²) version does about four million operations and passes. The two-sweep version is still the one interviewers expect because it shows the running-cost idea.
How is this related to Product of Array Except Self?
Both build each answer from a left part and a right part, using one sweep in each direction and combining the two partial results at every index.