Beats 99.83% | Easy code
\n\n# Intuition\n- The problem is about counting the minimum number of swaps needed to make a string of brackets balanced. The string s consists of square brack
![image.png](https://assets.leetcode.com/users/images/9ac37b89-e9b3-41f2-a974-9c34a2e83d78_1728369080.8800657.png)\n\n# Intuition\n- The problem is about counting the minimum number of swaps needed to make a string of brackets balanced. The string s consists of square brackets [ and ]. The goal is to balance these brackets by swapping.\n\n- If there are more closing brackets ] than opening brackets [ at any point, this means we have an imbalance.\nWe can "fix" the imbalance by swapping a closing bracket with an opening one from later in the string.\n- The key observation is that every mismatch increases the need for future swaps.\n# Approach\n1. Count Imbalances: As we traverse through the string, we track mismatches between opening and closing brackets. If we encounter more [ than ], the string is still balanced. If we encounter more ] than [, we accumulate an imbalance.\n2. Minimize Swaps: Whenever an imbalance occurs, we count how many opening brackets are required to fix it. The number of swaps required is (imbalance + 1) / 2 because two unmatched closing brackets will need to be swapped with two unmatched opening brackets.\n3. The result is how many swaps are needed to make the string balanced.\n# Complexity\n- Time Complexity\n    - O(n) where n is the length of the string s. We only traverse the string once.\n- Space Complexity:\n    - O(1) as we are using constant extra space for counting.\n---\n# Code\n```cpp []\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int cnt = 0;\n        for(const char & ch : s){\n            if(ch==\'[\') cnt++;\n            else if(cnt) cnt--;\n        }\n        return (cnt+1)/2;\n    }\n};\n```\n```Java []\nclass Solution {\n    public int minSwaps(String s) {\n        int cnt = 0;\n        \n        for (char ch : s.toCharArray()) {\n            if (ch == \'[\') cnt++;\n            else if (cnt > 0) cnt--;\n        }\n        \n        return (cnt + 1) / 2;\n    }\n}\n\n```\n```Python3 []\nclass Solution:\n    def minSwaps(self, s: str) -> int:\n        cnt = 0\n        \n        for ch in s:\n            if ch == \'[\':\n                cnt += 1\n            elif cnt > 0:\n                cnt -= 1\n        \n        return (cnt + 1) // 2\n\n```\n```Javascript []\nvar minSwaps = function(s) {\n    let cnt = 0;\n    \n    for (let ch of s) {\n        if (ch === \'[\') cnt++;\n        else if (cnt > 0) cnt--;\n    }\n    \n    return Math.floor((cnt + 1) / 2);\n};\n\n```\n![Please hit the upvote button (1).png](https://assets.leetcode.com/users/images/2b939ea7-646b-4252-85a2-7ef81a4ab99f_1728369127.2412264.png)\n\n
['String', 'Greedy', 'C++', 'Java', 'Python3', 'JavaScript']