August 11, 2022

921. Minimum Add to Make Parentheses Valid

921. Minimum Add to Make Parentheses Valid

Sol 1. Stack

Time: O(n), space: O(n)

class Solution {
    public int minAddToMakeValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(c);
            } else { // )
                if (!stack.isEmpty() && stack.peek() == '(') {
                    stack.pop();
                } else {
                    stack.push(c);
                }
            }
        }
        return stack.size();
    }
}

Sol 2. One pass

Time: O(n), space: O(1)

class Solution {
    public int minAddToMakeValid(String s) {
        int left = 0;
        int right = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                left++;
            } else {
                if (left > 0) {
                    left --;
                } else {
                    right ++;
                }
            }
        }
        return left + right;
    }

}
comments powered by Disqus