Fast and Intuitive Approach to Minimizing Swaps for Black Balls
Intuition\nThe problem requires moving all black balls (\'1\') to the rightmost side of the string with the minimum number of swaps. A good way to solve this is
# Intuition\nThe problem requires moving all black balls (\'1\') to the rightmost side of the string with the minimum number of swaps. A good way to solve this is by counting the number of \'1\'s encountered as we iterate through the string. Each time we encounter a \'0\', the number of swaps needed will be equal to the number of \'1\'s encountered so far, as these \'1\'s would need to be swapped past this \'0\'.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize two variables:\nblackBalls to keep track of the number of \'1\'s encountered (black balls).\n2. swapCount to accumulate the total number of swaps required.\nIterate through the string:\n-> If the current character is \'1\', increment blackBalls.\n-> If the current character is \'0\', add blackBalls to swapCount since all previously encountered \'1\'s would need to move past this \'0\'.\n\n3. Return the final value of swapCount, which gives the minimum number of swaps required.\n# Complexity\n- Time complexity:\n    O(n) , where n is the length of the string. We only traverse the string once\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n    O(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    long long minimumSteps(string s) {\n        long long int blackBalls = 0 , swapCount = 0;\n\n        for(int i = 0 ; i < s.length() ; i++){\n            if(s[i] == \'1\'){                         // 1 are black balls so store the number of black balls\n                blackBalls++;\n            }\n            else{\n                swapCount += blackBalls;             // count will be updated by the operations\n            }                                        //needed to move the black balls \n        }\n        return swapCount;\n    }\n};\n```
['String', 'C++']