Minimum Add to Make Parentheses Valid¶

Meta phone screen question (Software Engineer Machine Learning 2022).¶


The algorithm works as follow:

  1. Iterate over every parenthesis:
    • If the current parenthesis is a close parenthesis
      • If some unclosed open parenthesis remain then just decrease the number of unclosed open parenthesis by 1
      • If no unclosed open parenthesis remain then add one to the total
    • If the current parenthesis is an open parenthesis
      • Add one to the number of unclosed open parenthesis
  2. At the end add the number of remain unclosed open parenthesis to the total and return
In [ ]:
def minAddToMakeValid(s: str) -> int:
    counter_open, counter_total = 0, 0
    for parenthesis in s:
        if parenthesis == ")":
            # if the counter of available (unclosed) open parenthesis is 0 then we need to add 1 open parenthesis
            if counter_open==0:
                counter_total += 1
            # otherwise just use 1 open parenthesis and decrease the counter by 1
            else:
                counter_open -= 1
        else:
            counter_open += 1
    return(counter_total + counter_open)