Find a valid parenthesis sequence of length K from a given valid parenthesis sequence | Function to find the subsequence of length K forming valid sequence ; Stores the resultant String ; Check whether character at index i is visited or not ; Traverse the String ; Push index of open bracket ; Pop and mark visited ; Increment count by 2 ; Append the characters and create the resultant String ; Return the resultant String ; Driver Code ; Function call
function findString ( s , k ) { var n = s . length ; var ans = " " ; var st = [ ] ; var vis = new Array ( n ) ; List < bool > vis ( n , false ) ; var count = 0 ; for ( var i = 0 ; i < n ; ++ i ) { if ( s [ i ] === " " ) { st . push ( i ) ; } if ( count < k && s [ i ] === " " ) { vis [ st [ st . length - 1 ] ] = true ; st . pop ( ) ; vis [ i ] = true ; count += 2 ; } } for ( var i = 0 ; i < n ; ++ i ) { if ( vis [ i ] === true ) { ans += s [ i ] ; } } return ans ; } var s = " " ; var K = 2 ; document . write ( findString ( s , K ) ) ;