Skip to content
Related Articles

Related Articles

Improve Article

Reduce string by removing outermost parenthesis from each primitive substring

  • Last Updated : 17 May, 2021
Geek Week

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 susbstrings “(()())” + “(())”+”()”. After removing outermost parentheses of each priiimitive substrings, the string obtained is “()()” + “()” = “()()()”

Input: S = “((()())(())(()(())))” 
Output: ()()()()(())



 

Approach: Follow the steps below to solve the problem:

  1. Initialize a variable count to store the number of opening parentheses, i.e. ‘(‘.
  2. Add every ‘(‘ to the result if count is greater than 0, i.e. add all ‘(‘ after the first ‘(‘ of a primitive substring is encountered.
  3. Add every ‘)’ to the result if count is greater than 0, i.e. add all ‘)’ before the last ‘)’ of a primitive substring is encountered.
  4. Finally, print the resultant string obtained.

Below is the implementation of the above approach-

C++




// 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 string
string 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 Code
int main()
{
    string S = "(()())(())()";
    cout << removeOuterParentheses(S);
}

Java




// Java program to implement the
// above approach
import java.io.*;
class GFG{
   
// Function to remove the outermost
// parentheses of every primitive
// substring from the given string
static 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 Code
public static void main(String[] args)
{
  String S = "(()())(())()";
  System.out.print(removeOuterParentheses(S));
}
}
 
// This code is contributed by Chitranayal

Python3




# Python3 program to implement the
# above approach
 
# Function to remove the outermost
# parentheses of every primitive
# substring from the given string
def 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 Code
if __name__ == '__main__':
     
    S = "(()())(())()"
     
    print(removeOuterParentheses(S))
 
# This code is contributed by SURENDRA_GANGWAR

C#




// C# program to implement
// the above approach 
using System;
 
class GFG{
    
// Function to remove the outermost
// parentheses of every primitive
// substring from the given string
static 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 Code
public static void Main()
{
  string S = "(()())(())()";
   
  Console.Write(removeOuterParentheses(S));
}
}
 
// This code is contributed by sanjoy_62

Javascript




<script>
 
// Javascript program to implement the
// above approach
 
// Function to remove the outermost
// parentheses of every primitive
// substring from the given string
function removeOuterParentheses(S)
{
 
// Stores the resultant
// string
let res = "";
 
// Stores the count of
// opened parentheses
let count = 0;
 
// Traverse the string
for (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 string
return res;
}
 
// Driver Code
 
let S = "(()())(())()";
document.write(removeOuterParentheses(S));
 
// This code is contributed by jana_sayantan.
</script>
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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :