Leetcode #1769: Minimum Number of Operations to Move All Balls to Each Box
In this guide, we solve Leetcode #1769 Minimum Number of Operations to Move All Balls to Each Box in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, String, Prefix Sum
Intuition
Range queries become simple once we precompute cumulative sums.
We can transform subarray conditions into prefix comparisons.
Approach
Compute prefix sums and use a map to find matching prefixes.
This avoids nested loops while keeping the logic clear.
Steps:
- Compute prefix sums.
- Use a map to find valid ranges.
- Update the answer.
Example
Input: boxes = "110"
Output: [1,1,3]
Explanation: The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.
Python Solution
class Solution:
def minOperations(self, boxes: str) -> List[int]:
n = len(boxes)
left = [0] * n
right = [0] * n
cnt = 0
for i in range(1, n):
if boxes[i - 1] == '1':
cnt += 1
left[i] = left[i - 1] + cnt
cnt = 0
for i in range(n - 2, -1, -1):
if boxes[i + 1] == '1':
cnt += 1
right[i] = right[i + 1] + cnt
return [a + b for a, b in zip(left, right)]
Complexity
The time complexity is O(n). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.