Check if a given string can be converted to a Balanced Bracket Sequence | Function to check if the String can be balanced by replacing the ' $ ' with opening or closing brackets ; If String can never be balanced ; Declare 2 stacks to check if all ) can be balanced with ( or $ and vice - versa ; Store the count the occurence of ( , ) and $ ; Traverse the String ; Increment closed bracket count by 1 ; If there are no opening bracket to match it then return false ; Otherwise , pop the character from the stack ; If current character is an opening bracket or $ , push it to the stack ; Increment symbol count by 1 ; Increment open bracket count by 1 ; Traverse the String from end and repeat the same process ; If there are no closing brackets to match it ; Otherwise , pop character from stack ; Store the extra ( or ) which are not balanced yet ; Check if $ is available to balance the extra brackets ; Count ramaining $ after balancing extra ( and ) ; Check if each pair of $ is convertable in ( ) ; Driver Code ; Function Call
function canBeBalanced ( sequence ) { if ( sequence . length % 2 == 1 ) return false ; let stack_ = [ ] ; let stack2_ = [ ] ; let countOpen = 0 , countClosed = 0 ; let countSymbol = 0 ; for ( let i = 0 ; i < sequence . length ; i ++ ) { if ( sequence [ i ] == ' ' ) { countClosed ++ ; if ( stack_ . length == 0 ) { return false ; } else { stack_ . pop ( ) ; } } else { if ( sequence [ i ] == ' ' ) { countSymbol ++ ; } else { countOpen ++ ; } stack_ . push ( sequence [ i ] ) ; } } for ( let i = sequence . length - 1 ; i >= 0 ; i -- ) { if ( sequence [ i ] == ' ' ) { if ( stack2_ . length == 0 ) { return false ; } else { stack2_ . pop ( ) ; } } else { stack2_ . push ( sequence [ i ] ) ; } } let extra = Math . abs ( countClosed - countOpen ) ; if ( countSymbol < extra ) { return false ; } else { countSymbol -= extra ; if ( countSymbol % 2 == 0 ) { return true ; } } return false ; } let S = " " ; if ( canBeBalanced ( S ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }