921. Minimum Add to Make Parentheses Valid

can do with leetcode 301

T: O(n)

S : O(1)

class Solution {
    public int minAddToMakeValid(String s) {
        int count = 0;
        int remove = 0;
        for (char c : s.toCharArray()) {
            if (c == '(') {
                count++;
            } else if (c == ')') {
                count--;
            }
            if (count < 0) {
                count++;
                remove++;
            }
        }
        remove += count;
        return remove;
    }
}

Last updated