> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/stack-and-queue/1963.-minimum-number-of-swaps-to-make-the-string-balanced.md).

# 1963. Minimum Number of Swaps to Make the String Balanced

<figure><img src="https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2FWU7xU3mbAvxb7lRoq7wr%2Fimage.png?alt=media&amp;token=0569fd23-9f0a-48d3-9afc-ed756472abea" alt=""><figcaption></figcaption></figure>

T: O(n)

S: O(1)

```java
class Solution {
    public int minSwaps(String s) {
        int stackSize = 0;
        for (char c : s.toCharArray()) {
            if (c == '[') {
                stackSize++;
            } else {
                if (stackSize > 0) {
                    stackSize--;
                }
            }
        }
        return (stackSize + 1)/2;
    }
}
/**
[[]]

]]][[[
    
[]][][

[[][]]


]]][[[
c:1
o:0  
[]]][[  
  1
 */
```
