Find an equal point in a string of brackets | Method to find an equal index ; Store the number of opening brackets at each index ; Store the number of closing brackets at each index ; Check if there is no opening or closing brackets ; Check if there is any index at which both brackets are equal ; Driver Code
function findIndex ( str ) { let len = str . length ; let open = new Array ( len + 1 ) ; let close = new Array ( len + 1 ) ; for ( let i = 0 ; i < len + 1 ; i ++ ) { open [ i ] = 0 ; close [ i ] = 0 ; } let index = - 1 ; open [ 0 ] = 0 ; close [ len ] = 0 ; if ( str [ 0 ] == ' ' ) open [ 1 ] = 1 ; if ( str [ len - 1 ] == ' ' ) close [ len - 1 ] = 1 ; for ( let i = 1 ; i < len ; i ++ ) { if ( str [ i ] == ' ' ) open [ i + 1 ] = open [ i ] + 1 ; else open [ i + 1 ] = open [ i ] ; } for ( let i = len - 2 ; i >= 0 ; i -- ) { if ( str [ i ] == ' ' ) close [ i ] = close [ i + 1 ] + 1 ; else close [ i ] = close [ i + 1 ] ; } if ( open [ len ] == 0 ) return len ; if ( close [ 0 ] == 0 ) return 0 ; for ( let i = 0 ; i <= len ; i ++ ) if ( open [ i ] == close [ i ] ) index = i ; return index ; } let str = " " ; document . write ( findIndex ( str ) ) ;