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 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: 

  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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
#define ll long long
using namespace std;
 
// Function to find the subsequence
// of length K forming valid sequence
string 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 Code
int main()
{
    string s = "()()()";
    int K = 2;
 
    // Function Call
    cout << findString(s, K);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the subsequence
// of length K forming valid sequence
static 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 Code
public static void main(String[] args)
{
    String s = "()()()";
    int K = 2;
 
    // Function call
    System.out.print(findString(s, K));
}
}
 
// This code is contributed by gauravrajput1

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to find the subsequence
# of length K forming valid sequence
def 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 Code
if __name__ == '__main__':
     
    s = "()()()"
    K = 2
 
    # Function call
    print(findString(s, K))
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the
// subsequence of length
// K forming valid sequence
static 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 Code
public static void Main(String[] args)
{
  String s = "()()()";
  int K = 2;
 
  // Function call
  Console.Write(findString(s, K));
}
}
 
// This code is contributed by Princi Singh

chevron_right


Output: 

()




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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.