class Solution:
    def minAddToMakeValid(self, S):
        """
        :type S: str
        :rtype: int
        """
        count = 0
        openpara = 0
        size = len(S)
        i = 0
        while i < size:
            if S[i] == '(':
                openpara += 1   
            else:                   # the letter is ')'
                if openpara > 0:    # closing the open parenthesis
                    openpara -= 1
                else:
                    count += 1      # no open parenthesis ahead
            i += 1
        
        return count + abs(openpara)
        
        
s = Solution()
