🔧 Minimize Bracket Swaps in O(n): A Clear Step-by-Step Guide 🚀
 # Intuition\nThe problem seems to revolve around counting how many swaps are needed to balance a string of square brackets. The imbalance occurs when there are
<!-- # Intuition\nThe problem seems to revolve around counting how many swaps are needed to balance a string of square brackets. The imbalance occurs when there are more closing brackets (]) than opening brackets ([), and a swap is required to correct this imbalance.\n -->\n\n# Approach\n1. **Traverse the String:**\nWe iterate through the string character by character to process each bracket ([ or ]).\n2. **Counting Imbalance:**\nFor every closing bracket ], we check if there is an unmatched opening bracket [ available.\nIf there is no unmatched opening bracket (i.e., imbalance == 0), this indicates an imbalance because the closing bracket cannot be matched, and we increment the imbalance.\nIf there is an unmatched opening bracket (imbalance > 0), we decrease the imbalance, meaning the current closing bracket finds a match and balances the sequence.\nFor every opening bracket [, we increase the imbalance since we now have one more unmatched opening bracket.\n3. **Calculate Minimum Swaps:**\nAfter traversing the string, the imbalance variable holds the number of unmatched opening brackets.\nTo fix the imbalance, we can perform swaps, and each swap fixes two unmatched brackets (one closing and one opening).\nThe number of swaps required is calculated as **(imbalance + 1) / 2**. This formula ensures that we handle both even and odd imbalances correctly, as one swap can fix two brackets at a time.\n\n# Complexity\n- # Time complexity: \n    O(n) where n is the length of the string.\n\n- # Space complexity:\n    O(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int imbalance = 0;   // Tracks the imbalance between opening and closing brackets\n\n        // Traverse each character in the string\n        for (const char& ch : s) {\n            if (ch == \']\') {\n                // If a closing bracket is encountered\n                if (imbalance == 0) {\n                    // If no opening bracket is available, we need to "swap" it later\n                    imbalance++;  // Mark this as a new imbalance\n                } else {\n                    // Otherwise, there\'s an unmatched opening bracket available, balance it\n                    imbalance--;\n                }\n            } else {\n                // If an opening bracket is encountered, increase the imbalance\n                imbalance++;\n            }\n        }\n\n        // The final imbalance is divided by 2 (since one swap fixes two unmatched brackets)\n        return (imbalance + 1) / 2;\n    }\n};\n\n\n```\n![image.png](https://assets.leetcode.com/users/images/21478208-ccea-448b-b3b4-02574401edc0_1727318750.5181131.png)
['Two Pointers', 'String', 'Stack', 'Greedy', 'C++']