Convert an unbalanced bracket sequence to a balanced sequence | Function to return balancedBrackets string ; Initializing dep to 0 ; Stores maximum negative depth ; if dep is less than minDep ; if minDep is less than 0 then there is need to add ' ( ' at the front ; Reinitializing to check the updated string ; if dep is not 0 then there is need to add ' ) ' at the back ; Driver code
function balancedBrackets ( str ) { var dep = 0 ; var minDep = 0 ; for ( var i = 0 ; i < str . length ; i ++ ) { if ( str [ i ] === " " ) dep ++ ; else dep -- ; if ( minDep > dep ) minDep = dep ; } if ( minDep < 0 ) { for ( var i = 0 ; i < Math . abs ( minDep ) ; i ++ ) str = " " + str ; } dep = 0 ; for ( var i = 0 ; i < str . length ; i ++ ) { if ( str [ i ] === " " ) dep ++ ; else dep -- ; } if ( dep !== 0 ) { for ( var i = 0 ; i < dep ; i ++ ) str = str + " " ; } return str ; } var str = " " ; document . write ( balancedBrackets ( str ) ) ;