Greedy Solution with Explanation
The main stratergy is to keep track of the opening and closing brackets. Remove all the brackets which are in the correct position or balanced and then return t
The main stratergy is to keep track of the opening and closing brackets. Remove all the brackets which are in the correct position or balanced and then return the (number of remaining pairs + 1)/2.\n\nTo achieve this we use the stack data structure.\nConsider the string \n]]][][[[\n\nWhile iterating through the string we insert every \'[\' character into the stack and whenever we encounter a \']\' we pop a character from the stack if and only if the stack in not empty. As a result we end up removing all the brackets that were in the correct position.\n\n```\nclass Solution {\npublic:\n    int minSwaps(string a) {\n        \n        stack<char> s;\n        \n        for(auto child : a) {\n            if(child == \'[\') s.push(child);\n            else if(!s.empty()) s.pop();\n        }\n        \n        return (s.size() + 1)/2;\n    }\n};\n```\n**Time Complexity : O(N)\nSpace Complexity : O(N)**\n\nWe can further optimize the code in terms of the space complexity by replacing the stack with a variable which simulates the same function as that of the stack.\n\n```\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        \n        int countopen = 0;\n        \n        for(auto child : s) {\n            if(child == \'[\') countopen += 1;\n            else if(countopen) countopen -= 1;\n        }\n        \n        return (countopen + 1)/2;\n    }\n};\n```\n**Time Complexity : O(N)\nSpace Complexity : O(1)**\n\n*Please do upvote if you found this solution helpful.*
['Stack', 'Greedy', 'C', 'C++']