C++ || Balanced Bracket Approach ✅ | Complete Video Solution ✅✅
Complete Video Solution -\nhttps://www.youtube.com/watch?v=coNCShs30Gk&t=1030s\n\n# Intuition -\n- The logic is for every open , i am checking next closed brack
##### **Complete Video Solution** -\nhttps://www.youtube.com/watch?v=coNCShs30Gk&t=1030s\n\n# Intuition -\n- The logic is for every open , i am checking next closed bracket and removing that as they balance each other. At last the stack contains all the open brackets which are need to be swapped . So the max number of swaps will be half of the total unbalanced bracket because one swap balances 2.\n### Example 1-\n- Take it as our string -> \'] ] ] [ [ [\'\nThe stack size will be 3 as it will count for all the unbalanced bracket pairs.\nTo make it balance in min moves , you can swap first 2 brackets with last 2. Therefore you need only 2 swaps\n\n- First swap the 1st and Last bracket , we get 2 balanced pairs and just need 1 more pair, So will swap the 3rd and 4th bracket and finally get the result in 2 swaps\n\'] ] ] [ [ [\' -> \'[ ] ] [ [ ]\' -> \'[ ] [ ] [ ]\'\n\n### Example-2\n- Let take another example -    \'] ] ] ] [ [ [ [\' \n\n- The stack size will be 4 as unbalanced open brackets are 4 , So to balance it we will swap 1st and last bracket first\nwhich will eventually make it like this\n\'] ] ] ] [ [ [ [\' -> \'[ ] ] ] ] [ [ [ ]\'\n- You can clearly see that we got 2 balanced pairs with just 1 swap , Similarly with just 1 more swap of 3rd and 6th bracket , we can balance it fully.\n\'[ ] ] ] ] [ [ [ ]\' - >   \'[ ] [ ] [ ] [ ]\'\n- The total swaps are 2 only.\n```\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int ans=0;\n        stack<char> stack;\n        for(int i=0;i<s.length();i++){\n            if(s[i]==\'[\'){\n                stack.push(s[i]);\n            }\n            if(s[i]==\']\' && stack.size()!=0 && stack.top()==\'[\'){\n                stack.pop();\n            }\n            \n        }\n        \n        ans=stack.size();\n        if(ans%2==0)\n            return ans/2;\n        else\n            return (ans+1)/2;\n        \n\n    }\n};\n```\n\nTime Complexity - O(N)\nSpace Complexity - O(1)\n\nTo optimise the space further, instead of stack you can use the variable which will help in calculating the number of open bracket which was earlier stored in stack.\n\nCode - \n```\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int size = 0;\n        \n        for(char &ch : s) {\n            if(ch == \'[\')      size++;\n            else if(size != 0) size--;\n        }\n        \n        return (size+1)/2;\n    }\n};\n```\n\nSpace Complexity - O(1)\n\nIf you have found this helpful, please upvote.\n\n![image](https://assets.leetcode.com/users/images/34948e00-112e-4db6-8808-49449f2bb570_1728388240.2689319.jpeg)\n
['Stack', 'C', 'C++']