Minimum swaps to balance the given brackets at any index | Function to balance the given bracket by swap ; To count the number of uunbalanced pairs ; if there is an opening bracket and we encounter closing bracket then it will decrement the count of unbalanced bracket . ; else it will increment unbalanced pair count ; Driver code
def BalancedStringBySwapping ( s ) : NEW_LINE INDENT unbalancedPair = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( unbalancedPair > 0 and s [ i ] == ' ] ' ) : NEW_LINE INDENT unbalancedPair -= 1 ; NEW_LINE DEDENT elif ( s [ i ] == ' [ ' ) : NEW_LINE INDENT unbalancedPair += 1 ; NEW_LINE DEDENT DEDENT return ( unbalancedPair + 1 ) // 2 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : s = " ] ] ] [ [ [ " ; NEW_LINE INDENT print ( BalancedStringBySwapping ( s ) ) ; NEW_LINE DEDENT