Kotlin. Beats 100% (196 ms). Static cache (8-bit chunks)
\n\n# Code\nkotlin []\nclass Solution {\n    fun minimumSteps(s: String): Long {\n        var swaps = 0L\n        var white = 0\n\n        var byte = 0\n       
![image.png](https://assets.leetcode.com/users/images/ee9b1476-3c28-4127-a2da-2cceccbddd60_1728980740.4372792.png)\n\n# Code\n```kotlin []\nclass Solution {\n    fun minimumSteps(s: String): Long {\n        var swaps = 0L\n        var white = 0\n\n        var byte = 0\n        var bits = 0\n        for (i in s.length - 1 downTo 0) {\n            byte = byte or ((s[i] - \'0\') shl bits)\n            if (bits++ == 7) {\n                swaps += swapCache[byte] + blackCache[byte] * white\n                white += whiteCache[byte]\n                bits = 0\n                byte = 0\n            }\n        }\n        if (bits > 0) swaps += swapCache[byte] + blackCache[byte] * white\n        return swaps\n    }\n\n    companion object {\n        val swapCache = LongArray(256) {\n            var n = it\n            var swaps = 0L\n            var white = 0\n            for (i in 0 until 8) {\n                if (n and 1 == 1) swaps += white else white++\n                n = n shr 1\n            }\n            swaps\n        }\n        val blackCache = IntArray(256) { Integer.bitCount(it) }\n        val whiteCache = IntArray(256) { 8 - blackCache[it] }\n    }\n}\n```\n\n# Approach\n\nWhen optimizing the performance of an algorithm, we should always pay attention to the moments when the algorithm starts "riding the same tracks".\n\nIn this case, we can group all the bits from the "s" string into 8-bit chunks and see that the counters of swap operations are repeated from chunk to chunk, with the exception that the accumulated number of white balls will need to be added to each swap operation from a new chunk.\n\nWe can replace several summations of swaps with white balls from previous chunks with multiplication. According to measurements (Beats 100% of users with Kotlin), the trick with grouping into 8-bit chunks and caching works.\n\n# Alternative approach\n\n1. Simple solution\n\n![image.png](https://assets.leetcode.com/users/images/eb5fb67d-b046-4365-97fe-4d5bf0dd9394_1728982087.4955697.png)\n\n```\nfun minimumSteps(s: String): Long {\n    var swaps = 0L\n    var white = 0\n    for (i in s.length - 1 downTo 0) {\n        if (s[i] == \'1\') swaps += white else white++\n    }\n    return swaps\n}\n```\n\n2. Reducing steps if no white balls left\n\n![{CA93E124-EBEE-4DCA-91F1-63B694745CCF}.png](https://assets.leetcode.com/users/images/63a1ad28-e8c7-4ac6-b432-5b7167cd4d58_1729002458.2332628.png)\n\n```\nclass Solution {\n    fun minimumSteps(s: String): Long {\n        var white = s.length\n        for (c in s) white -= c - \'0\'\n\n        var swap = 0L\n        for (c in s) {\n            if (c == \'1\') swap += white else if (--white == 0) break\n        }\n        return swap\n    }\n}\n```
['Kotlin']