Minimum number of Parentheses to be added to make it valid | Function to return required minimum number ; maintain balance of string ; It is guaranteed bal >= - 1 ; Driver code ; Function to print required answer
def minParentheses ( p ) : NEW_LINE INDENT bal = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , len ( p ) ) : NEW_LINE INDENT if ( p [ i ] == ' ( ' ) : NEW_LINE INDENT bal += 1 NEW_LINE DEDENT else : NEW_LINE INDENT bal += - 1 NEW_LINE DEDENT if ( bal == - 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE bal += 1 NEW_LINE DEDENT DEDENT return bal + ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = " ( ) ) " NEW_LINE print ( minParentheses ( p ) ) NEW_LINE DEDENT