✅ Beats 100% | Working 08.10.2024 | Explained Step by Step
python3 []\nclass Solution:\n    def minSwaps(self, s: str) -> int:\n        # Initialize a variable to keep track of unmatched opening brackets\n        stack_
```python3 []\nclass Solution:\n    def minSwaps(self, s: str) -> int:\n        # Initialize a variable to keep track of unmatched opening brackets\n        stack_size = 0\n\n        # Iterate through each character in the input string\n        for ch in s:\n            if ch == "[":\n                # If we encounter an opening bracket, increment the stack size\n                stack_size += 1\n            else:\n                # If we encounter a closing bracket\n                if stack_size > 0:\n                    # If there\'s a matching opening bracket (stack_size > 0),\n                    # decrement the stack size\n                    stack_size -= 1\n                \n\n        # Calculate the minimum number of swaps needed\n        # We need to swap half of the remaining unmatched brackets\n        # Use integer division (//) and add 1 to round up for odd numbers\n        return (stack_size + 1) // 2\n```\n```cpp []\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        // Initialize a variable to keep track of the stack size\n        int stack_size = 0;\n\n        // Iterate through each character in the input string\n        for (char ch : s) {\n            if (ch == \'[\') {\n                // If we encounter an opening bracket, increase the stack size\n                stack_size++;\n            } else {\n                // If we encounter a closing bracket\n                if (stack_size > 0) {\n                    // If there\'s a matching opening bracket (stack_size > 0),\n                    // decrease the stack size\n                    stack_size--;\n                }\n            }\n        }\n\n        // Calculate the minimum number of swaps needed\n        // We need to swap half of the remaining unmatched brackets\n        // Use (stack_size + 1) / 2 for integer division rounding up\n        return (stack_size + 1) / 2;\n    }\n};\n```\n```java []\nclass Solution {\n    public int minSwaps(String s) {\n        // Initialize a variable to keep track of unmatched opening brackets\n        int stackSize = 0;\n\n        // Iterate through each character in the input string\n        for (char ch : s.toCharArray()) {\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                \n            }\n        }\n\n        // Calculate the minimum number of swaps needed\n        // We need to swap half of the remaining unmatched brackets\n        // Use integer division and add 1 to round up for odd numbers\n        return (stackSize + 1) / 2;\n    }\n}\n```\n```javascript [JS]\n/**\n * @param {string} s\n * @return {number}\n */\nvar minSwaps = function(s) {\n    // Initialize a variable to keep track of unmatched opening brackets\n    let stackSize = 0;\n\n    // Iterate through each character in the input string\n    for (let ch of s) {\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 Math.floor to round down the division result after adding 1\n    return Math.floor((stackSize + 1) / 2);\n};\n```\n```typescript [TS]\nfunction minSwaps(s: string): number {\n    // Initialize a variable to keep track of unmatched opening brackets\n    let stackSize: number = 0;\n\n    // Iterate through each character in the input string\n    for (let ch of s) {\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 Math.floor to round down the division result after adding 1\n    return Math.floor((stackSize + 1) / 2);\n}\n```\n```csharp []\npublic class Solution {\n    public int MinSwaps(string s) {\n        // Initialize counters for unmatched opening and closing brackets\n        int open = 0;   // Count of unmatched opening brackets\n        int close = 0;  // Count of unmatched closing brackets\n\n        // Iterate through each character in the input string\n        foreach(var c in s)\n        {\n            if(c == \'[\')\n                // If we encounter an opening bracket, increment the \'open\' counter\n                open++;\n            else if(c == \']\')\n            {\n                if(open > 0)\n                    // If there\'s an unmatched opening bracket, match it with this closing bracket\n                    open--;\n                else\n                    // If there\'s no unmatched opening bracket, this is an unmatched closing bracket\n                    close++;\n            }\n        }\n\n        // Calculate the minimum number of swaps needed\n        // We need to swap half of the unmatched closing brackets, plus one more if the count is odd\n        return close / 2 + (close % 2);\n    }\n}\n```\n```golang []\nfunc minSwaps(s string) int {\n    // Initialize variables to keep track of closing brackets and maximum imbalance\n    var close, maxClose int\n\n    // Iterate through each character in the string\n    for _, c := range s {\n        if c == \']\' {\n            // If we encounter a closing bracket, increment the \'close\' counter\n            close++\n            // Update maxClose to be the maximum of current maxClose and close\n            // This keeps track of the maximum imbalance we\'ve seen so far\n            maxClose = max(maxClose, close)\n        } else {\n            // If we encounter an opening bracket \'[\', decrement the \'close\' counter\n            // This balances out a previous closing bracket\n            close--\n        }\n    }\n\n    // The minimum number of swaps needed is (maxClose + 1) / 2\n    // This formula works because:\n    // 1. We need to balance out the maximum imbalance we\'ve seen (maxClose)\n    // 2. Each swap can fix two imbalances (it moves a \'[\' to the left and a \']\' to the right)\n    // 3. We round up using (x + 1) / 2 to handle odd numbers of imbalances\n    return (maxClose + 1) / 2\n}\n```\n```rust [Rust(8ms)]\nimpl Solution {\n    pub fn min_swaps(s: String) -> i32 {\n        let mut stack_size = 0;\n        \n        // Iterate through each character in the string\n        for ch in s.chars() {\n            if ch == \'[\' {\n                // If we encounter an opening bracket, increment stack size\n                stack_size += 1;\n            } else if ch == \']\' {\n                // If we encounter a closing bracket and have unmatched opening brackets,\n                // decrement stack size\n                if stack_size > 0 {\n                    stack_size -= 1;\n                }\n            }\n        }\n        \n        // The minimum number of swaps needed is (remaining unmatched brackets + 1) / 2\n        (stack_size + 1) / 2\n    }\n}\n```\n```ruby []\n# @param {String} s\n# @return {Integer}\ndef min_swaps(s)\n  # Initialize a variable to keep track of unmatched opening brackets\n  stack_size = 0\n\n  # Iterate through each character in the input string\n  s.each_char do |ch|\n    if ch == \'[\'\n      # If we encounter an opening bracket, increment the stack size\n      stack_size += 1\n    else\n      # If we encounter a closing bracket\n      if stack_size > 0\n        # If there\'s a matching opening bracket (stack_size > 0),\n        # decrement the stack size\n        stack_size -= 1\n      end\n      # If stack_size is 0, it means we have an unmatched closing bracket,\n      # but we don\'t need to do anything special for this case\n    end\n  end\n\n  # Calculate the minimum number of swaps needed\n  # We need to swap half of the remaining unmatched brackets\n  # Use integer division to round down the result after adding 1\n  (stack_size + 1) / 2\nend\n\n# impresive solution from k_duder https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/solutions/5884247/1-liner/\n```\n```swift []\nclass Solution {\n    func minSwaps(_ s: String) -> Int {\n        // Initialize a variable to keep track of unmatched opening brackets\n        var stackSize = 0\n        \n        // Iterate through each character in the input string\n        for ch in s {\n            if ch == "[" {\n                // If we encounter an opening bracket, increment the stack size\n                stackSize += 1\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 -= 1\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 integer division and add 1 to round up for odd numbers\n        return (stackSize + 1) / 2\n    }\n}\n```\n### Explained Step by Step\n\n1. We start by initializing a variable `stack_size ` to **0** \nThis variable will keep track of the number of unmatched opening brackets as we iterate through the string.\n\n2. We then iterate through each character in the input string s:\n-  2.a. If we encounter an opening bracket "[", we increment `stack_size ` by **1** . This is because we\'ve found an opening bracket that hasn\'t been matched yet.\n- 2.b.. If we encounter a closing bracket "]", we check if `stack_size `is greater than 0. If it is, it means we have an unmatched opening bracket available, so we can match it with this closing bracket. In this case, we decrement `stack_size ` by **1**.\n3. After iterating through the entire string, `stack_size` will represent the number of **unmatched** opening brackets.\n4. To calculate the minimum number of swaps needed, we use the formula `(stack_size + 1) // 2`:\n\n-  We need to swap half of the unmatched brackets because each swap fixes two brackets (it moves a "[" to the right and a "]" to the left).\n- We add 1 before dividing by 2 to handle cases where stack_size is odd. This ensures we round up to the nearest integer.\n- We use integer division (`//`) to get the final result as an integer.\n\nThats the the reason this solution works is that it effectively counts the number of mismatched brackets and then calculates how many swaps are needed to fix them.\n\nBy keeping track of unmatched opening brackets, so **we can determine how many closing brackets are out of place**.\n\n...and efficient bcs only one pass through the string and dont need extra space \n**time: O(n) space: O(1)**\n\nIs it understandable? Do you have any suggestions on how I could write this more clearly? Please for contrictive critisis.\n\n### Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n![image.png](https://assets.leetcode.com/users/images/d3fb1458-e28f-4e28-a063-77b208ce4311_1728347924.1229765.png)\n\n![image.png](https://assets.leetcode.com/users/images/9dc1b265-b175-4bf4-bc6c-4b188cb79220_1728176037.4402142.png)\n\n
['Swift', 'C++', 'Java', 'Go', 'TypeScript', 'Python3', 'Rust', 'Ruby', 'JavaScript', 'C#']