text: Minimum Swaps for Bracket Balancing | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; long swapCount ( string chars ) { int countLeft = 0 , countRight = 0 ; int swap = 0 , imbalance = 0 ; for ( int i = 0 ; i < chars . length ( ) ; i ++ ) { if ( chars [ i ] == ' [ ' ) { countLeft ++ ; if ( imbalance > 0 ) { swap += imbalance ; imbalance -- ; } } else if ( chars [ i ] == ' ] ' ) { countRight ++ ; imbalance = ( countRight - countLeft ) ; } } return swap ; } int main ( ) { string s = " [ ] ] [ ] [ " ; cout << swapCount ( s ) << endl ; s = " [ [ ] [ ] ] " ; cout << swapCount ( s ) << endl ; return 0 ; }