C++ Two Pointers
\n\nSee my latest update in repo LeetCode\n\n## Solution 1. Two Pointers\n\nIntuition: We keep looking for the first unmatched ] from left and the first unmatch
\n\nSee my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Two Pointers\n\n**Intuition**: We keep looking for the first unmatched `]` from left and the first unmatched `[` from the right, and swap them.\n\n**Algorithm**: Use two pointers `L = 0, R = N - 1`, and two counters `left` and `right` which are the number of unmatched `[`/`]` from left/right, respectively. For example, if we\'ve seen `[[]` from the left, then `left = 1` because there is one `[` unmatched.\n\nWe keep incrementing `L` and decrementing `R` until `left` and `right` become `-1`. And we swap `s[L]` and `s[R]` and set `left = right = 1`.\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-253/problems/minimum-number-of-swaps-to-make-the-string-balanced/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int left = 0, right = 0, N = s.size(), L = 0, R = N - 1, ans = 0; \n        while (L < R) {\n            for (; L < R; ++L) {\n                left += s[L] == \'[\' ? 1 : -1;\n                if (left == -1) break;\n            }\n            if (L >= R) break; // no more unmatched branchets, break\n            for (; L < R; --R) {\n                right += s[R] == \']\' ? 1 : -1;\n                if (right == -1) break;\n            }\n            left = right = 1; // after swapping `s[L]` and `s[R]`, `left` and `right` will become `1`.\n            ++L, --R;\n            ++ans;\n        }\n        return ans;\n    }\n};\n```\n\n## Solution 2. Two Pointers\n\nThanks @nkmnikhil\n\nFind the first unmatched `[` from the left, and swap it with the first `]` from the right.\n\n```cpp\n// OJ: https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n    int minSwaps(string s) {\n        int N = s.size(), cnt = 0, i = 0, j = N - 1, ans = 0;\n        for (int i = 0; i < j; ++i) {\n            cnt += s[i] == \'[\' ? 1 : -1;\n            if (cnt == -1) {\n                while (s[j] == \']\') --j;\n                cnt = 1;\n                ++ans;\n            }\n        }\n        return ans;\n    }\n};\n```
[]