Separate Black and White Balls (easy cpp approach) Leetcode -2938
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem can be seen as counting the number of operations required to convert a stri
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem can be seen as counting the number of operations required to convert a string such that every \'0\' appears after all \'1\'s. For each \'0\' in the string, we count how many \'1\'s have appeared before it and add that count to the total number of operations.\n\nThis can be explained as follows:\n\n- Each \'0\' needs to be swapped with each \'1\' that appears before it to maintain the order of \'1\'s before \'0\'s. Thus, for every \'0\', we accumulate the number of preceding \'1\'s.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize two variables:\n- `cnt` to store the cumulative number of \'1\'s encountered.\n- `ans` to store the total number of steps required.\n2. Traverse the string character by character:\n- If the character is \'1\', increment cnt because each \'1\' can potentially contribute to future swaps with \'0\'s.\n- If the character is \'0\', increment `ans` by the value of `cnt` because each \'0\' needs to be swapped with all the preceding \'1\'s.\n3. After traversing the string, return `ans` as the result, which represents the minimum steps required.\n\n# Complexity\n- Time complexity: The time complexity is O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: he space complexity is O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    long long minimumSteps(string s) {\n  \n  long long cnt=0; // to store count of \'1\'(appeared before \'0\'******Bold******)\n long long ans=0; \n  for(int i=0;i<s.size();i++)\n  {\n    if(s[i]==\'1\')\n    cnt+=1; // increasing cnt \n\n    else\n    ans+=cnt; // if s[i]==0 then add cnt to ans \n\n  }\n\n\n     return ans;   \n    }\n};\n```
['C++']