LC 0921 [M] Minimum Add to Make Parentheses Valid - ALawliet/algorithms GitHub Wiki

same algo as minimum remove to make parens valid except no need to map out the string without the invalids, just count the number of invalids, so also don't even need a set for duplicate invalid indexes

class Solution:
    def minAddToMakeValid(self, s: str) -> int:
        l = 0
        r = 0
        
        for i, x in enumerate(s):
            if x == '(':
                l += 1
            elif x == ')':
                if l:
                    l -= 1
                else:
                    r += 1
        
        unpaired = l + r
        
        return unpaired