Minimum Add to Make Parentheses Valid

Problem Id: 921 Difficulty: Medium


Intuition

Solution


class Solution:
    def minAddToMakeValid(self, S: str) -> int:
        stack = 0
        ans = 0
        for c in S:
            if c == '(':
                stack += 1
            elif ')':
                if stack == 0:
                    ans += 1
                else:
                    stack -= 1
        ans += stack
        return ans