text: Minimum Swaps for Bracket Balancing | Python3 program to count swaps required to balance string ; Stores total number of left and right brackets encountered ; Swap stores the number of swaps required imbalance maintains the number of imbalance pair ; Increment count of left bracket ; Swaps count is last swap count + total number imbalanced brackets ; Imbalance decremented by 1 as it solved only one imbalance of left and right ; Increment count of right bracket ; Imbalance is reset to current difference between left and right brackets ; Driver code
code: def swapCount ( s ) : NEW_LINE INDENT chars = s NEW_LINE countLeft = 0 NEW_LINE countRight = 0 NEW_LINE swap = 0 NEW_LINE imbalance = 0 ; NEW_LINE for i in range ( len ( chars ) ) : NEW_LINE INDENT if chars [ i ] == ' [ ' : NEW_LINE INDENT countLeft += 1 NEW_LINE if imbalance > 0 : NEW_LINE INDENT swap += imbalance NEW_LINE imbalance -= 1 NEW_LINE DEDENT DEDENT elif chars [ i ] == ' ] ' : NEW_LINE INDENT countRight += 1 NEW_LINE imbalance = ( countRight - countLeft ) NEW_LINE DEDENT DEDENT return swap NEW_LINE DEDENT s = " [ ] ] [ ] [ " ; NEW_LINE print ( swapCount ( s ) ) NEW_LINE s = " [ [ ] [ ] ] " ; NEW_LINE print ( swapCount ( s ) ) NEW_LINE