Minimum operation required to make a balanced sequence | Function to return the minimum operations required ; Condition where we got only one closing bracket instead of 2 , here we have to add one more closing bracket to make the sequence balanced ; Add closing bracket that costs us one operation ; Remove the top opening bracket because we got the 1 opening and 2 continuous closing brackets ; Inserting the opening bracket to stack ; After making the sequence balanced closing is now set to 0 ; Case when there is no opening bracket the sequence starts with a closing bracket and one opening bracket is required Now we have one opening and one closing bracket ; Add opening bracket that costs us one operation ; Assigning 1 to cntClosing because we have one closing bracket ; Case where we got two continuous closing brackets Need to pop one opening bracket from stack top ; Condition where stack is not empty This is the case where we have only opening brackets ( st . size ( ) * 2 ) will give us the total closing bracket needed cntClosing is the count of closing bracket that we already have ; Driver code
function minOperations ( s , len ) { var operationCnt = 0 ; var st = [ ] ; var cntClosing = 0 ; for ( var i = 0 ; i < len ; i ++ ) { if ( s [ i ] == ' ' ) { if ( cntClosing > 0 ) { operationCnt ++ ; st . pop ( ) ; } st . push ( s [ i ] ) ; cntClosing = 0 ; } else if ( st . length == 0 ) { st . push ( ' ' ) ; operationCnt ++ ; cntClosing = 1 ; } else { cntClosing = ( cntClosing + 1 ) % 2 ; if ( cntClosing == 0 ) { st . pop ( ) ; } } } operationCnt += st . length * 2 - cntClosing ; return operationCnt ; } var str = " " ; var len = str . length ; document . write ( minOperations ( str , len ) ) ;