Beginner Friendly Solution ✅ ✅
\n# Approach\n\n1. Initialize a variable open to keep track of how many opening brackets are left unmatched as you iterate through the string.\n\n2. Loop throug
\n# Approach\n\n1. Initialize a variable open to keep track of how many opening brackets are left unmatched as you iterate through the string.\n\n2. Loop through the string character by character:\n\n- If you encounter an opening bracket `\'[\'`, increase the open count.\n- If you encounter a closing bracket `\']\'`, check if there\'s an unmatched opening bracket (open > 0). If so, you balance it by decreasing open. If not, you leave the unbalanced closing bracket as it is.\n\n3. At the end of the loop, the open count will tell you how many unbalanced opening brackets are left. The number of swaps required to balance them is calculated by (open + 1) // 2. This formula works because every two unbalanced opening brackets will need one swap to fix.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int open = 0; // Track unbalanced opening brackets\n        \n        // Traverse the string\n        for(auto c : s) {\n            if (c == \'[\') \n                open++; // Found an opening bracket, increase the count\n            else if (open > 0) \n                open--; // Found a closing bracket, balance it with an opening bracket if available\n        }\n        \n        // Return the minimum number of swaps needed to balance the remaining unbalanced opening brackets\n        return (open + 1) / 2;\n    }\n};\n```\n# Example Walkthrough:\n**Example 1:**\nInput: `"][]["`\n\n1. Traverse:\n\n- `]` (open = 0) -> No unmatched opening bracket to balance it, string is unbalanced here.\n- `[` (open = 1) -> Found an opening bracket.\n- `]` (open = 0) -> Balanced with an unmatched opening bracket.\n- `[` (open = 1) -> Another unmatched opening bracket.\n2. At the end of the traversal, open = 1.\n\n3 .The number of swaps required: (1 + 1) // 2 = `1` swap.\n\nExample 2:\nInput: "]]]][[[["\n\n1. Traverse:\n\n- `]` (open = 0) -> Unbalanced.\n- `]` (open = 0) -> Unbalanced.\n- `]` (open = 0) -> Unbalanced.\n- `]` (open = 0) -> Unbalanced.\n- `[` (open = 1) -> Found an opening bracket.\n- `[` (open = 2) -> Found an opening bracket.\n- `[` (open = 3) -> Found an opening bracket.\n- `[` (open = 4) -> Found an opening bracket.\n\n2. At the end of the traversal, open = 4.\n\n3. The number of swaps required: (4 + 1) // 2 = `2` swaps\n\n# Complexity\n- Time complexity:\n**O(n)** where n is the length of the string. You only traverse the string once to count unbalanced brackets.\n\n- Space complexity:\n**O(1)** as we are only using a few variables to keep track of the unbalanced brackets.
['String', 'C++']