# Find a valid parenthesis sequence of length K from a given valid parenthesis sequence

• Difficulty Level : Medium
• Last Updated : 24 May, 2021

Given a string S of valid parentheses sequence of length N and an even integer K, the task is to find the valid parentheses sequence of length K which is also a subsequence of the given string.

Note: There can be more than one valid sequence, print any of them.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Examples:

Input: S = “()()()”, K = 4
Output: ()()
Explanation:
The string “()()” is a subsequence of length 4 which is a valid parenthesis sequence.

Input: S = “()(())”, K = 6
Output: ()(())
Explanation:
The string “()(())” is a subsequence of length 6 which is a valid parenthesis sequence.

Naive Approach: The idea is to generate all possible subsequences of length K of the given string and print any of the string having a valid parenthesis sequence.
Time Complexity: O(2N)
Auxiliary Space: O(K)

Efficient Approach: The above approach can be optimized using a Stack. The idea is to traverse the given string and when an open parenthesis character is encountered, push it to the stack else, pop a character from it. Correspondingly, increment the counter every time a character is popped. Follow the below steps to solve the problem:

1. Create a stack and the boolean array, initialized to false.
2. Traverse the given string and if an opening parenthesis is encountered, push that index into the stack.
3. Otherwise, if a closing brace is encountered:
• Pop the top element from the stack
• Increment the counter by 2
• Mark popped and current indices as true.
4. If the counter exceeds K, terminate.
5. After traversing, append all the characters together, from left to right, which is marked true. Print the resultant string formed.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach #include #define ll long longusing namespace std; // Function to find the subsequence// of length K forming valid sequencestring findString(string s, int k){    int n = s.length();     // Stores the resultant string    string ans = "";    stack st;     // Check whether character at    // index i is visited or not    vector vis(n, false);    int count = 0;     // Traverse the string    for (int i = 0; i < n; ++i) {         // Push index of open bracket        if (s[i] == '(') {            st.push(i);        }         // Pop and mark visited        if (count < k && s[i] == ')') {             vis[st.top()] = 1;            st.pop();            vis[i] = true;             // Increment count by 2            count += 2;        }    }     // Append the characters and create    // the resultant string    for (int i = 0; i < n; ++i) {         if (vis[i] == true) {            ans += s[i];        }    }     // Return the resultant string    return ans;} // Driver Codeint main(){    string s = "()()()";    int K = 2;     // Function Call    cout << findString(s, K);}

## Java

 // Java program for the above approachimport java.util.*; class GFG{ // Function to find the subsequence// of length K forming valid sequencestatic String findString(String s, int k){    int n = s.length();     // Stores the resultant String    String ans = " ";    Stack st = new Stack<>();     // Check whether character at    // index i is visited or not    boolean []vis = new boolean[n];         // Vector vis(n, false);    int count = 0;     // Traverse the String    for(int i = 0; i < n; ++i)    {                 // Push index of open bracket        if (s.charAt(i) == '(')        {            st.add(i);        }         // Pop and mark visited        if (count < k && s.charAt(i) == ')')        {            vis[st.peek()] = true;            st.pop();            vis[i] = true;             // Increment count by 2            count += 2;        }    }     // Append the characters and create    // the resultant String    for(int i = 0; i < n; ++i)    {        if (vis[i] == true)        {            ans += s.charAt(i);        }    }     // Return the resultant String    return ans;} // Driver Codepublic static void main(String[] args){    String s = "()()()";    int K = 2;     // Function call    System.out.print(findString(s, K));}} // This code is contributed by gauravrajput1

## Python3

 # Python3 program for the above approach # Function to find the subsequence# of length K forming valid sequencedef findString(s, k):         n = len(s)     # Stores the resultant string    ans = ""    st = []     # Check whether character at    # index i is visited or not    vis = [False] * n    count = 0     # Traverse the string    for i in range(n):         # Push index of open bracket        if (s[i] == '('):            st.append(i)         # Pop and mark visited        if (count < k and s[i] == ')'):            vis[st[-1]] = 1            del st[-1]            vis[i] = True             # Increment count by 2            count += 2     # Append the characters and create    # the resultant string    for i in range(n):        if (vis[i] == True):            ans += s[i]                 # Return the resultant string    return ans # Driver Codeif __name__ == '__main__':         s = "()()()"    K = 2     # Function call    print(findString(s, K)) # This code is contributed by mohit kumar 29

## C#

 // C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the// subsequence of length// K forming valid sequencestatic String findString(String s,                         int k){  int n = s.Length;   // Stores the resultant String  String ans = " ";  Stack st = new Stack();   // Check whether character at  // index i is visited or not  bool []vis = new bool[n];   // List vis(n, false);  int count = 0;   // Traverse the String  for(int i = 0; i < n; ++i)  {    // Push index of open bracket    if (s[i] == '(')    {      st.Push(i);    }     // Pop and mark visited    if (count < k && s[i] == ')')    {      vis[st.Peek()] = true;      st.Pop();      vis[i] = true;       // Increment count by 2      count += 2;    }  }   // Append the characters and create  // the resultant String  for(int i = 0; i < n; ++i)  {    if (vis[i] == true)    {      ans += s[i];    }  }   // Return the resultant String  return ans;} // Driver Codepublic static void Main(String[] args){  String s = "()()()";  int K = 2;   // Function call  Console.Write(findString(s, K));}} // This code is contributed by Princi Singh

## Javascript


Output:
()

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up