Minimum number of Parentheses to be added to make it valid | Function to return required minimum number ; maintain balance of string ; It is guaranteed bal >= - 1 ; Driver code ; Function to print required answer
function minParentheses ( p ) { var bal = 0 ; var ans = 0 ; for ( var i = 0 ; i < p . length ; ++ i ) { bal += p [ i ] == ' ' ? 1 : - 1 ; if ( bal == - 1 ) { ans += 1 ; bal += 1 ; } } return bal + ans ; } var p = " " ; document . write ( minParentheses ( p ) ) ;