Minimum swaps to balance the given brackets at any index | C ++ implementation for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int BalancedStringBySwapping ( string s ) { int unbalancedPair = 0 ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( unbalancedPair > 0 && s [ i ] == ' ] ' ) { -- unbalancedPair ; } else if ( s [ i ] == ' [ ' ) { ++ unbalancedPair ; } } return ( unbalancedPair + 1 ) / 2 ; } int main ( ) { string s = " ] ] ] [ [ [ " ; cout << ( BalancedStringBySwapping ( s ) ) ; return 0 ; }