Beats 99.83% || C++ || Two Pointers || Intuitive
Intuition\n Describe your first thoughts on how to solve this problem. \nIn a balanced expression at any index, number of closing brackets remain either less or
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn a balanced expression at any index, number of closing brackets remain either less or equal to the opening brackets.\nWe can use a variable closing (initialised with 0), to indicate number of closing brackets - number of opening brackets till now.\nIf we encounter opening bracket then closing--\nIf we encounter closing bracket then closing++\n\nAs soon as we get closing > 0, it means an imbalance has occur, so we will swap current closing bracket with the opening bracket that is closest to the right end, and simultaneously we decrease closing by 2, since now we have opening bracket in place of closing.\n\n# Complexity \n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int n = s.size();\n        int ans = 0;\n        int closing = 0, j = n-1;\n        for(int i=0; i<j; i++){\n            if(s[i] == \'[\') closing--;\n            if(s[i] == \']\'){\n                closing++;\n                if(closing > 0){\n                    ans++;\n                    while(s[j]!=\'[\') j--;\n                    swap(s[i], s[j]);\n                    closing -= 2;\n                    j--;\n                }\n            }\n        }\n        return ans;\n    }\n};\nauto speedup = [](){ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0;}();\n```
['Two Pointers', 'String', 'Greedy', 'C++']