🔥 C++ || 100% Faster || Dynamic Index Tracking || Easy to Understand 💡
IntuitionThe problem requires calculating the minimum operations to move all 1s in a binary string boxes to every position. Initially, my intuition was to focus
# Intuition
The problem requires calculating the minimum operations to move all `1`s in a binary string `boxes` to every position. Initially, my intuition was to focus on precomputing the cumulative impact of `1`s across the string to minimize redundant calculations. Each position's value can be derived from the cumulative distances of `1`s on its left and right.

# Approach
1. **Initialization:** 
   - Use variables `total_index` and `number_of_ones` to track the total index sum of all `1`s and their count.
   - Use `prev_ones` and `prev_index` to efficiently calculate contributions from already processed positions.

2. **First Pass:** 
   - Calculate the sum of indices (`total_index`) and count of all `1`s (`number_of_ones`) in the string.
   
3. **Second Pass:** 
   - For each box:
     - If it contains a `0`, calculate its value based on the total distance to all `1`s.
     - If it contains a `1`, calculate its value, then update `number_of_ones`, `total_index`, `prev_index`, and `prev_ones` for subsequent calculations.

4. **Result:** 
   - Store the results in the `values` vector and return it.

# Complexity
- **Time complexity:**  
  $$O(n)$$, where $$n$$ is the length of the string. This includes:
  - $$O(n)$$ for the first pass to calculate `total_index` and `number_of_ones`.
  - $$O(n)$$ for the second pass to compute the values.

- **Space complexity:**  
  $$O(n)$$ for the `values` vector used to store results.

# Code
```cpp
class Solution {
public:
    vector<int> minOperations(string boxes) {

        vector<int>values(boxes.size());
        int total_index = 0;
        int number_of_ones = 0;
        int prev_ones = 0, prev_index = 0;

        for(int i = 0; i < boxes.size(); i++) {
            if(boxes[i] == '1') {
                total_index += i;
                number_of_ones++;
            }
        }

        for(int i = 0; i < boxes.size(); i++) {
            if(boxes[i] == '0') {
                values[i] = (total_index - (i * number_of_ones)) + abs((prev_ones * i) - prev_index);
            } else {
                values[i] = (total_index - i - (i * (number_of_ones - 1))) + abs((prev_ones * i) - prev_index);
                number_of_ones--;
                total_index -= i;
                prev_index += i;
                prev_ones++;
            }
        }

        return values;
    }
};

['Prefix Sum', 'C++']