1963. Minimum Number of Swaps to Make the String Balanced

T: O(n)

S: O(1)

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
 */

Last updated

Was this helpful?