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
def findString ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = " " NEW_LINE st = [ ] NEW_LINE vis = [ False ] * n NEW_LINE count = 0 NEW_LINE List < bool > vis ( n , false ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT st . append ( i ) NEW_LINE DEDENT if ( count < k and s [ i ] == ' ) ' ) : NEW_LINE INDENT vis [ st [ - 1 ] ] = 1 NEW_LINE del st [ - 1 ] NEW_LINE vis [ i ] = True NEW_LINE count += 2 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] == True ) : NEW_LINE INDENT ans += s [ i ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " ( ) ( ) ( ) " NEW_LINE K = 2 NEW_LINE print ( findString ( s , K ) ) NEW_LINE DEDENT