Modify a numeric string to a balanced parentheses by replacements | Function to check if the given string can be converted to a balanced bracket sequence or not ; Check if the first and last characters are equal ; Initialize two variables to store the count of open and closed brackets ; If the current character is same as the first character ; If the current character is same as the last character ; If count of open brackets becomes less than 0 ; Print the new string ; If the current character is same as the first character ; If bracket sequence is not balanced ; Check for unbalanced bracket sequence ; Print the sequence ; Given Input ; Function Call
function balBracketSequence ( str ) { let n = str . length ; if ( str [ 0 ] == str [ n - 1 ] ) { document . write ( " " ) ; } else { let cntForOpen = 0 , cntForClose = 0 ; let check = 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cntForOpen ++ ; else if ( str [ i ] == str [ n - 1 ] ) cntForOpen -- ; else cntForOpen ++ ; if ( cntForOpen < 0 ) { check = 0 ; break ; } } if ( check && cntForOpen == 0 ) { document . write ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ n - 1 ] ) document . write ( ' ' ) ; else document . write ( ' ' ) ; } return ; } else { for ( let i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cntForClose ++ ; else cntForClose -- ; if ( cntForClose < 0 ) { check = 0 ; break ; } } if ( check && cntForClose == 0 ) { document . write ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) document . write ( ' ' ) ; else document . write ( ' ' ) ; } return ; } } document . write ( " " ) ; } } let str = " " ; balBracketSequence ( str ) ;