TC - O(n) Space Complexity - O(1) Excluding result space
We Dont need extra spaces for prefix and postfix count of '1'. Just get prefix and postfix for index one in O(n) and modify both at each index to get updated pr
We Dont need extra spaces for prefix and postfix count of '1'. Just get prefix and postfix for index one in O(n) and modify both at each index to get updated prefix and postfix count for that particular index.

**First look on the last approach to understand first approach.**
# Complexity
- Time complexity:
O(n)

- Space complexity:
O(1) excluding answer array

# Code
```cpp []
class Solution {
public:
    vector<int> minOperations(string boxes) {
        int n = boxes.size();
        vector<int>ans(n,0);
        int pre = boxes[0] == '1', post = 0;

        for(int i=1;i<n;i++){
            if(boxes[i] == '1'){
                post++;
                ans[0] += i;
            }
        }
        
        for(int i=1;i<n;i++){
            if(boxes[i] == '1')
                post--;

            ans[i] = ans[i-1] - post - (boxes[i] == '1') + pre;

            if(boxes[i] == '1')
                pre++;
        }
        
        return ans;
    }
};
```

Above approach intuition from Below approach

# Code
```cpp []
class Solution {
public:
    vector<int> minOperations(string boxes) {
        int n = boxes.size();
        vector<int>ans(n,0);
        vector<int>pre(n,0);
        vector<int>post(n,0);
        
        pre[0] = boxes[0] == '1';
        post[n-1] = boxes[n-1] == '1';

        for(int i=0,j=n-1;i<n;i++,j--){
            if(i>0){
                pre[i] = pre[i-1] + (boxes[i] == '1');
                ans[0] += (boxes[i] == '1') ? i : 0;
            }
            if(j<n-1)
                post[j] = post[j+1] + (boxes[j] == '1');
        }
        
        for(int i=1;i<n;i++)
            ans[i] = ans[i-1] - post[i] - (boxes[i] == '1') + pre[i];
        
        return ans;
    }
};
```
['C++']