Back to Month
MEDIUM 06 Oct 2026 View on LeetCode

921. Minimum Add to Make Parentheses Valid

</> Solution

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

TIME COMPLEXITY

O(n)

SPACE COMPLEXITY

O(1)

TOPICS

Array Greedy Parentheses String