Beats 100% Easy Counter Solution 🧠 Python | Java | C++
Intuition\nTo minimize the number of swaps, we calculate the number of swaps required by counting how many white balls (0) we need to skip as we encounter black
# Intuition\nTo minimize the number of swaps, we calculate the number of `swaps` required by counting how many `white balls (0)` we need to skip as we encounter `black balls (1)` that are out of place. \n\n**Every time a** `black ball (1)` **appears before a** `white ball (0)`, **it means we would need to swap that black ball to the right.**\n\n# Approach\n1. We count how many `black balls (1)` we have encountered so far.\n2. Every time we encounter a `white ball (0)`, it can be thought of as a **swap opportunity**, where a black ball should have taken that position.\n3. The `total number of swaps` == `sum of the "swap opportunities"` for every black ball (1) we encounter.\n\nInitialization of two variables:\n- `swap`: This variable tracks the total number of swaps needed.\n- `black`: This variable tracks the number of \'1\'s encountered so far as we iterate through the string.\n\n> **Thank you for your upvote in advance \u2B06\uFE0F**\n\n# Complexity\n- Time complexity: $$O(N)$$\n    - Traversing the input string `s`\n\n- Space complexity: $$O(1)$$\n    - Using two variables and therefore constant\n\n# Code\n```python3 []\nclass Solution:\n    def minimumSteps(self, s: str) -> int:\n        swap, black = 0, 0\n        for c in s:\n            if c == "0":\n                swap += black\n            else:\n                black += 1\n        return swap\n```\n```java []\nclass Solution {\n    public long minimumSteps(String s) {\n        long swap = 0;\n        int black = 0; \n        for (int i = 0; i < s.length(); i++) {\n            if (s.charAt(i) == \'0\') \n                swap += (long) black; \n            else\n                black++; \n        }\n        return swap;\n    }\n}\n```\n```C++ []\nclass Solution {\npublic:\n    long long minimumSteps(string s) {\n        long long swap = 0;\n        int black = 0; \n        for (int i = 0; i < s.length(); i++) {\n            if (s[i] == \'0\') \n                swap += (long long) black; \n            else\n                black++; \n        }\n        return swap;\n    }\n};\n```\n> **Thank you for your upvote in advance \u2B06\uFE0F**\n\n![image.png](https://assets.leetcode.com/users/images/47429397-2f8a-4e9e-9b2f-95d6b4f25138_1728951045.1803987.png)
['Counting', 'C++', 'Java', 'Python3']