C++ Solution || O(1) Solution || Detailed explanation
Intuition\nThe problem seems to involve balancing parentheses (square brackets in this case). The goal is to determine how many swaps are needed to balance a st
# Intuition\nThe problem seems to involve balancing parentheses (square brackets in this case). The goal is to determine how many swaps are needed to balance a string of square brackets. Every time there is an imbalance (i.e., more closing brackets `]` than opening brackets `[`), we need to track it, and eventually, the imbalance can be resolved by making swaps.\n\n# Approach\n1. The code iterates through the string, using a counter `cnt` to track how balanced the string is. For every opening bracket `[`, the counter increases by 1, and for every closing bracket `]`, if there are unmatched opening brackets (i.e., `cnt > 0`), the counter decreases by 1, meaning the closing bracket is matched with an earlier opening bracket.\n\n2. The unmatched opening brackets are counted in `cnt` at the end of the loop. If the string has unbalanced opening and closing brackets, it means that we need to make swaps to balance them.\n\n3. Since each swap can fix two unmatched brackets, the result is `(cnt + 1) / 2`. This is because we round up to account for any odd imbalance, as one swap can resolve two brackets.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int cnt = 0;\n        for (char& ch : s) {\n            if (ch == \'[\') {\n                cnt++;\n            } else if (cnt > 0) {\n                cnt--;\n            }\n        }\n        return (cnt + 1) / 2;\n    }\n};\n```\n\n> ***Life\u2019s like a string of brackets\u2014if it\u2019s balanced, you\u2019re doing great. If it\u2019s not, welcome to debugging.***\n\n![1721315779911.jpeg](https://assets.leetcode.com/users/images/34902ff2-d1c4-401d-ba5f-92a8331b0bc5_1728380694.2649643.jpeg)\n
['String', 'C++']