Two Passes and O(1) Extra Space - O(n) | C++, Python, Java
ApproachWe can efficiently calculate the result for each answer[i] using a prefix sum array prefix which will store the prefix sum for the right-to-left pass. H
# Approach
We can efficiently calculate the result for each `answer[i]` using a prefix sum array `prefix` which will store the prefix sum for the right-to-left pass. However, for this problem we can use the resulting array `res` initially as our prefix sum array and then update the values in the second pass.

`count` keeps track of the cumulative cost of moving all the balls encountered so far and `x` counts the number of balls encountered so far. For every new ball we encounter, that counts as an extra move (to the right) we have to do to move them to each index. Thus, `res[i]` holds the cost of moving all balls (to the left of the current index) to that index $$i$$.

We reuse the method above for the second pass to always have the cost of moving all balls to the current index but this time moving from left to right. Thus at each index, the minimum operations needed to move all the balls to the current index would be `res[i] + count` (i.e move all balls from the left + move all balls from the right). 

# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```C++ []
class Solution {
public:
    vector<int> minOperations(string boxes) {
        vector<int> res;
        int n = boxes.length();
        for (int i = 0, count = 0, x = 0; i < n; i++){
            res.push_back(count);
            x += boxes[i] - '0';
            count += x;
        }
        for (int i = n - 1, count = 0, x = 0; i >= 0; i--){
            res[i] += count;
            x += boxes[i] - '0';
            count += x;
        }
        return res;
    }
};
```
```python []
class Solution:
    def minOperations(self, boxes: str) -> List[int]:
        res = []
        n = len(boxes)
        count = x = 0
        for i in range(n):
            res.append(count)
            x += int(boxes[i])
            count += x

        count = x = 0
        for i in range(n - 1, -1, -1):
            res[i] += count
            x += int(boxes[i])
            count += x

        return res
```
```Java []
class Solution {
    public int[] minOperations(String boxes) {
        int n = boxes.length();
        int[] res = new int[n];
        int count = 0, x = 0;
        for (int i = 0; i < n; i++) {
            res[i] = count;
            x += boxes.charAt(i) - '0';
            count += x;
        }
        count = 0;
        x = 0;
        for (int i = n - 1; i >= 0; i--) {
            res[i] += count;
            x += boxes.charAt(i) - '0';
            count += x;
        }
        return res;
    }
}
```

['Array', 'String', 'C', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3']