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 subsequence of the given string.
Note: There can be more than one valid sequence, print any of them.
Input: S = “()()()”, K = 4
The string “()()” is a subsequence of length 4 which is a valid parenthesis sequence.
Input: S = “()(())”, K = 6
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:
- Create a stack and the boolean array, initialized to false.
- Traverse the given string and if an opening parenthesis is encountered, push that index into the stack.
- 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.
- If the counter exceeds K, terminate.
- 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:
Time Complexity: O(N)
Auxiliary Space: O(N)
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.