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

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.
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:
- 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:
C++
// C++ program for the above approach#include <bits/stdc++.h>#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<int> st; // Check whether character at // index i is visited or not vector<bool> 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<Integer> st = new Stack<>(); // Check whether character at // index i is visited or not boolean []vis = new boolean[n]; // Vector<boolean> 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<int> st = new Stack<int>(); // Check whether character at // index i is visited or not bool []vis = new bool[n]; // List<bool> 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
<script> // JavaScript program for // the above approach // Function to find the // subsequence of length // K forming valid sequence function findString(s, k) { var n = s.length; // Stores the resultant String var ans = " "; var st = []; // Check whether character at // index i is visited or not var vis = new Array(n); // List<bool> vis(n, false); var count = 0; // Traverse the String for (var 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[st.length - 1]] = true; st.pop(); vis[i] = true; // Increment count by 2 count += 2; } } // Append the characters and create // the resultant String for (var i = 0; i < n; ++i) { if (vis[i] === true) { ans += s[i]; } } // Return the resultant String return ans; } // Driver Code var s = "()()()"; var K = 2; // Function call document.write(findString(s, K)); </script> |
()
Time Complexity: O(N) where n is number of elements in given string. As, we are using a loop to traverse N times so it will cost us O(N) time
Auxiliary Space: O(N), as we are using extra space for stack.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



