Open In App

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: 

  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++ 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);
}




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




# 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




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




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

Output: 
()

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.


Article Tags :