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++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
string findString(string s, int k)
{
int n = s.length();
string ans = "" ;
stack< int > st;
vector< bool > vis(n, false );
int count = 0;
for ( int i = 0; i < n; ++i) {
if (s[i] == '(' ) {
st.push(i);
}
if (count < k && s[i] == ')' ) {
vis[st.top()] = 1;
st.pop();
vis[i] = true ;
count += 2;
}
}
for ( int i = 0; i < n; ++i) {
if (vis[i] == true ) {
ans += s[i];
}
}
return ans;
}
int main()
{
string s = "()()()" ;
int K = 2;
cout << findString(s, K);
}
|
Java
import java.util.*;
class GFG{
static String findString(String s, int k)
{
int n = s.length();
String ans = " " ;
Stack<Integer> st = new Stack<>();
boolean []vis = new boolean [n];
int count = 0 ;
for ( int i = 0 ; i < n; ++i)
{
if (s.charAt(i) == '(' )
{
st.add(i);
}
if (count < k && s.charAt(i) == ')' )
{
vis[st.peek()] = true ;
st.pop();
vis[i] = true ;
count += 2 ;
}
}
for ( int i = 0 ; i < n; ++i)
{
if (vis[i] == true )
{
ans += s.charAt(i);
}
}
return ans;
}
public static void main(String[] args)
{
String s = "()()()" ;
int K = 2 ;
System.out.print(findString(s, K));
}
}
|
Python3
def findString(s, k):
n = len (s)
ans = ""
st = []
vis = [ False ] * n
count = 0
for i in range (n):
if (s[i] = = '(' ):
st.append(i)
if (count < k and s[i] = = ')' ):
vis[st[ - 1 ]] = 1
del st[ - 1 ]
vis[i] = True
count + = 2
for i in range (n):
if (vis[i] = = True ):
ans + = s[i]
return ans
if __name__ = = '__main__' :
s = "()()()"
K = 2
print (findString(s, K))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static String findString(String s,
int k)
{
int n = s.Length;
String ans = " " ;
Stack< int > st = new Stack< int >();
bool []vis = new bool [n];
int count = 0;
for ( int i = 0; i < n; ++i)
{
if (s[i] == '(' )
{
st.Push(i);
}
if (count < k && s[i] == ')' )
{
vis[st.Peek()] = true ;
st.Pop();
vis[i] = true ;
count += 2;
}
}
for ( int i = 0; i < n; ++i)
{
if (vis[i] == true )
{
ans += s[i];
}
}
return ans;
}
public static void Main(String[] args)
{
String s = "()()()" ;
int K = 2;
Console.Write(findString(s, K));
}
}
|
Javascript
<script>
function findString(s, k) {
var n = s.length;
var ans = " " ;
var st = [];
var vis = new Array(n);
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));
</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.