Minimum Number of Operations to Move All Balls to Each Box — LeetCode 1769 Python Solution

MediumArrayStringPrefix Sum
Problem
#1769
Pattern
Prefix Sum
Reading time
3 min

The problem

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.

Example

Input
boxes = "110"
Output
[1,1,3]
Explanation
The answer for each box is as follows:

Python solution

Python
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

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box?
LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box is rated Medium on LeetCode.
What is the time complexity of LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box cover?
LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box is tagged Array, String and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview