Php, Kotlin, Dart | Working 08.10.2024
Code\nphp []\nclass Solution {\n    /**\n     * @param String $s\n     * @return Integer\n     */\n    function minSwaps($s) {\n        // Initialize a variable
# Code\n```php []\nclass Solution {\n    /**\n     * @param String $s\n     * @return Integer\n     */\n    function minSwaps($s) {\n        // Initialize a variable to keep track of unmatched opening brackets\n        $stackSize = 0;\n\n        // Iterate through each character in the input string\n        for ($i = 0; $i < strlen($s); $i++) {\n            $ch = $s[$i];\n            if ($ch === \'[\') {\n                // If we encounter an opening bracket, increment the stack size\n                $stackSize++;\n            } else {\n                // If we encounter a closing bracket\n                if ($stackSize > 0) {\n                    // If there\'s a matching opening bracket (stackSize > 0),\n                    // decrement the stack size\n                    $stackSize--;\n                }\n                // If stackSize is 0, it means we have an unmatched closing bracket,\n                // but we don\'t need to do anything special for this case\n            }\n        }\n\n        // Calculate the minimum number of swaps needed\n        // We need to swap half of the remaining unmatched brackets\n        // Use intdiv to perform integer division after adding 1\n        return intdiv($stackSize + 1, 2);\n    }\n}\n```\n```kotlin []\nclass Solution {\n    fun minSwaps(s: String): Int {\n        var stack = 0\n        var swaps = 0\n        for((i,c) in s.withIndex()){\n            if(c == \'[\') stack++\n            else if(c == \']\' && stack == 0) { swaps++; stack++ }\n            else stack--\n        }\n        return swaps\n    }\n}\n```\n```Dart []\nclass Solution {\n  int minSwaps(String s) {\n    int count =0;\nint maxImbalance =0;\n    for(int i=0;i<s.length;i++){\n        if(s[i]==\'[\'){\n            count--;\n        }else{\n            count++;\n        }\n        if(count>maxImbalance){\n            maxImbalance = count;\n        }\n    }\n  int  ans =  ((maxImbalance + 1) /2).toInt();\n    return ans;\n  }\n}\n```\n\n### Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\nC++, C#, Python3, Java, TypeScript, Javascript, GOlang, Ruby, Rust and Swift Solution here:\nhttps://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/solutions/5884240/beats-100-working-08-10-2024-explained/\n\n![image.png](https://assets.leetcode.com/users/images/d441b945-b575-4f27-a7b1-64f15799ca1b_1728349775.989746.png)\n![image.png](https://assets.leetcode.com/users/images/9dc1b265-b175-4bf4-bc6c-4b188cb79220_1728176037.4402142.png)\n
['PHP', 'Kotlin', 'Dart']