Easiest Java Solution 🧠 Beats 100% | O(N) TIME and O(1) Space
This is the easiest solution you may find of this problem.\n# Intuition\nThe problem involves separating black and white balls represented as a binary string, w
This is the easiest solution you may find of this problem.\n# Intuition\nThe problem involves separating black and white balls represented as a binary string, where \'1\' stands for a black ball and \'0\' for a white ball. To achieve the desired arrangement of all \'0\'s to the left and all \'1\'s to the right, we need to determine the minimum number of adjacent swaps required. The key insight is that every black ball (\'1\') will need to swap with any white ball (\'0\') that is to its left, which can be counted as we traverse the string.\n\n# Approach\nInitialize Counters: Create variables to keep track of the number of white balls encountered (whiteCount) and the total number of swaps needed (swaps).\nTraverse the String: Iterate through the string from right to left:\nIf the character is \'0\', increment the whiteCount.\nIf the character is \'1\', add the current whiteCount to swaps, as this represents the number of adjacent swaps needed for that black ball to reach its correct position.\nReturn the Result: After the loop, the total swaps will represent the minimum steps required to group all black balls to the right.\n\n# Complexity\n\nTime complexity: O(n)\nSpace complexity:O(1)\n\nThis solution efficiently counts the necessary swaps with a single traversal of the string and uses a constant amount of additional space.\n\n# Code\n```java []\nclass Solution {\n    public long minimumSteps(String s) {\n        long whiteCount = 0;\n        long swaps = 0;      \n\n        for (int i = s.length() - 1; i >= 0; i--) {\n            if (s.charAt(i) == \'0\') {\n                whiteCount++;\n            } else {\n                swaps += whiteCount;\n            }\n        }\n\n        return swaps; \n    }\n}\n\n```
['Two Pointers', 'String', 'Greedy', 'Java']