Two Pointers
We go left to right (i), and track open and closed brackets in bal. When bal goes negative, we have an orphan ]. \n\nTo balance it out, we need to find an orpha
We go left to right (`i`), and track open and closed brackets in `bal`. When `bal` goes negative, we have an orphan `]`. \n\nTo balance it out, we need to find an orphaned `[` and swap those two. So, we go right-to-left (`j`), and we can search for the orphaned `[`. \n\nWhy is this strategy optimal? Because we have to fix all orphaned `]` and `[` brackets. The optimal strategy is to fix two brackets with one swap.\n\n#### Alternative Solution\nSee the original solution for additional details. To find the number of swaps, we can just count all orphaned `]` (or `[`) in `cnt`. The answer is `(cnt + 1) / 2` to fix the string, since one swap matches 4 brackest (or two in the last swap - if `cnt` is odd.\n\nThis solution was inspired by our conversation with [digvijay91](https://leetcode.com/digvijay91/) (see comments for additional details).\n\n**C++**\n```cpp\nint minSwaps(string s) {\n    int bal = 0, cnt = 0;\n    for (auto ch : s)\n        if (bal == 0 && ch == \']\')\n            ++cnt;\n        else\n            bal += ch == \'[\' ? 1 : -1;\n    return (cnt + 1) / 2;\n}\n```\n\n#### Original Solution\n**C++**\n```cpp\nint minSwaps(string s) {\n    int res = 0, bal = 0;\n    for (int i = 0, j = s.size() - 1; i < j; ++i) {\n        bal += s[i] == \'[\' ? 1 : -1;\n        if (bal < 0) {\n            for (int bal1 = 0; bal1 >= 0; --j)\n                bal1 += s[j] == \']\' ? 1 : -1;\n            swap(s[i], s[j + 1]);\n            ++res;\n            bal = 1;\n        }\n    }\n    return res;\n}\n```\n**Python 3**\n```python\nclass Solution:\n    def minSwaps(self, s: str) -> int:\n        res, bal = 0, 0\n        for ch in s:\n            bal += 1 if ch == \'[\' else -1\n            if bal == -1:\n                res += 1\n                bal = 1\n        return res\n```
['C', 'Python3']