text: Minimum Swaps for Bracket Balancing | Function to calculate swaps required ; Keep track of '[ ; To count number of encountered ' [ ' ; To track position of next ' [ ' in pos ; To store result ; Increment count and move p to next position ; We have encountered an unbalanced part of string ; Increment sum by number of swaps required i . e . position of next ' [ ' - current position ; Reset count to 1 ; Driver code
code: def swapCount ( s ) : NEW_LINE ' NEW_LINE INDENT pos = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' [ ' ) : NEW_LINE INDENT pos . append ( i ) NEW_LINE DEDENT DEDENT count = 0 NEW_LINE p = 0 NEW_LINE sum = 0 NEW_LINE s = list ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' [ ' ) : NEW_LINE INDENT count += 1 NEW_LINE p += 1 NEW_LINE DEDENT elif ( s [ i ] == ' ] ' ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count < 0 ) : NEW_LINE INDENT sum += pos [ p ] - i NEW_LINE s [ i ] , s [ pos [ p ] ] = ( s [ pos [ p ] ] , s [ i ] ) NEW_LINE p += 1 NEW_LINE count = 1 NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT s = " [ ] ] [ ] [ " NEW_LINE print ( swapCount ( s ) ) NEW_LINE s = " [ [ ] [ ] ] " NEW_LINE print ( swapCount ( s ) ) NEW_LINE