Convert an unbalanced bracket sequence to a balanced sequence | Function to return balancedBrackets String ; Initializing dep to 0 ; Stores maximum negative depth ; if dep is less than minDep ; if minDep is less than 0 then there is need to add ' ( ' at the front ; Reinitializing to check the updated String ; if dep is not 0 then there is need to add ' ) ' at the back ; Driver code
def balancedBrackets ( Str ) : NEW_LINE INDENT dep = 0 NEW_LINE minDep = 0 NEW_LINE for i in Str : NEW_LINE INDENT if ( i == ' ( ' ) : NEW_LINE INDENT dep += 1 NEW_LINE DEDENT else : NEW_LINE INDENT dep -= 1 NEW_LINE DEDENT if ( minDep > dep ) : NEW_LINE INDENT minDep = dep NEW_LINE DEDENT DEDENT if ( minDep < 0 ) : NEW_LINE INDENT for i in range ( abs ( minDep ) ) : NEW_LINE INDENT Str = ' ( ' + Str NEW_LINE DEDENT DEDENT dep = 0 NEW_LINE for i in Str : NEW_LINE INDENT if ( i == ' ( ' ) : NEW_LINE INDENT dep += 1 NEW_LINE DEDENT else : NEW_LINE INDENT dep -= 1 NEW_LINE DEDENT DEDENT if ( dep != 0 ) : NEW_LINE INDENT for i in range ( dep ) : Str = Str + ' ) ' NEW_LINE DEDENT return Str NEW_LINE DEDENT Str = " ) ) ) ( ) " NEW_LINE print ( balancedBrackets ( Str ) ) NEW_LINE