Reduce string by removing outermost parenthesis from each primitive substring

28 May, 2022
Given a string S of valid parentheses “(“ and “)”, the task is to print the string obtained by removing the outermost parentheses of every primitive substring from S.
A valid parentheses substring S is primitive if it is non-empty, and cannot be split into two or more non-empty substrings which are also a valid parentheses.
Examples:
Input: S = “(()())(())()” Output: ()()() Explanation: The input string is “(()())(())()” can be decomposed into primitive substrings “(()())” + “(())”+”()”. After removing outermost parentheses of each priiimitive substrings, the string obtained is “()()” + “()” = “()()()”
Input: S = “((()())(())(()(())))” Output: ()()()()(())
Approach: Follow the steps below to solve the problem:
Initialize a variable count to store the number of opening parentheses, i.e. ‘(‘.Add every ‘(‘ to the result if count is greater than 0, i.e. add all ‘(‘ after the first ‘(‘ of a primitive substring is encountered.Add every ‘)’ to the result if count is greater than 0, i.e. add all ‘)’ before the last ‘)’ of a primitive substring is encountered.Finally, print the resultant string obtained.
Initialize a variable count to store the number of opening parentheses, i.e. ‘(‘.
Add every ‘(‘ to the result if count is greater than 0, i.e. add all ‘(‘ after the first ‘(‘ of a primitive substring is encountered.
Add every ‘)’ to the result if count is greater than 0, i.e. add all ‘)’ before the last ‘)’ of a primitive substring is encountered.
Finally, print the resultant string obtained.
Below is the implementation of the above approach-
C++
Java
Python3
C#
Javascript
// C++ program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to remove the outermost// parentheses of every primitive// substring from the given stringstring removeOuterParentheses(string S){     // Stores the resultant string    string res;     // Stores the count of    // opened parentheses    int count = 0;     // Traverse the string    for (char c : S) {         // If opening parenthesis is        // encountered and their        // count exceeds 0        if (c == '(' && count++ > 0)             // Include the character            res += c;         // If closing parenthesis is        // encountered and their        // count is less than count        // of opening parentheses        if (c == ')' && count-- > 1)             // Include the character            res += c;    }     // Return the resultant string    return res;} // Driver Codeint main(){    string S = "(()())(())()";    cout << removeOuterParentheses(S);}
// Java program to implement the// above approachimport java.io.*;class GFG{   // Function to remove the outermost// parentheses of every primitive// substring from the given stringstatic String removeOuterParentheses(String S){  // Stores the resultant  // string  String res = "";   // Stores the count of  // opened parentheses  int count = 0;   // Traverse the string  for (int c = 0;           c < S.length(); c++)  {    // If opening parenthesis is    // encountered and their    // count exceeds 0    if (S.charAt(c) == '(' &&        count++ > 0)       // Include the character      res += S.charAt(c);     // If closing parenthesis is    // encountered and their    // count is less than count    // of opening parentheses    if (S.charAt(c) == ')' &&        count-- > 1)       // Include the character      res += S.charAt(c);  }   // Return the resultant string  return res;} // Driver Codepublic static void main(String[] args){  String S = "(()())(())()";  System.out.print(removeOuterParentheses(S));}} // This code is contributed by Chitranayal
# Python3 program to implement the# above approach # Function to remove the outermost# parentheses of every primitive# substring from the given stringdef removeOuterParentheses(S):         # Stores the resultant string    res = ""     # Stores the count of    # opened parentheses    count = 0     # Traverse the string    for c in S:                 # If opening parenthesis is        # encountered and their        # count exceeds 0        if (c == '(' and count > 0):             # Include the character            res += c         # If closing parenthesis is        # encountered and their        # count is less than count        # of opening parentheses        if (c == '('):            count += 1        if (c == ')' and count > 1):             # Include the character            res += c                     if (c == ')'):          count -= 1         # Return the resultant string    return res # Driver Codeif __name__ == '__main__':         S = "(()())(())()"         print(removeOuterParentheses(S)) # This code is contributed by SURENDRA_GANGWAR
// C# program to implement// the above approach using System; class GFG{    // Function to remove the outermost// parentheses of every primitive// substring from the given stringstatic string removeOuterParentheses(string S){     // Stores the resultant  // string  string res = "";    // Stores the count of  // opened parentheses  int count = 0;    // Traverse the string  for(int c = 0; c < S.Length; c++)  {         // If opening parenthesis is    // encountered and their    // count exceeds 0    if (S == '(' &&        count++ > 0)        // Include the character      res += S;      // If closing parenthesis is    // encountered and their    // count is less than count    // of opening parentheses    if (S == ')' &&        count-- > 1)        // Include the character      res += S;  }    // Return the resultant string  return res;}  // Driver Codepublic static void Main(){  string S = "(()())(())()";     Console.Write(removeOuterParentheses(S));}} // This code is contributed by sanjoy_62
<script> // Javascript program to implement the// above approach // Function to remove the outermost// parentheses of every primitive// substring from the given stringfunction removeOuterParentheses(S){ // Stores the resultant// stringlet res = ""; // Stores the count of// opened parentheseslet count = 0; // Traverse the stringfor (let c = 0;        c < S.length; c++){    // If opening parenthesis is    // encountered and their    // count exceeds 0    if (S.charAt(c) == '(' &&        count++ > 0)     // Include the character    res += S.charAt(c);     // If closing parenthesis is    // encountered and their    // count is less than count    // of opening parentheses    if (S.charAt(c) == ')' &&        count-- > 1)     // Include the character    res += S.charAt(c);} // Return the resultant stringreturn res;} // Driver Code let S = "(()())(())()";document.write(removeOuterParentheses(S)); // This code is contributed by jana_sayantan.</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.
ukasp
SURENDRA_GANGWAR
sanjoy_62
jana_sayantan
varshagumber28
rohitkumarsinghcna
frequency-counting
substring
Mathematical
Searching
Strings
Searching
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array