Reduce string by removing outermost parentheses from each primitive substring
Last Updated :
03 May, 2023
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 primitive 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 1, 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++
// 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 parentheses is
// encountered and their
// count exceeds 0
if (c == '(' && count++ > 0)
// Include the character
res += c;
// If closing parentheses 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 parentheses is
// encountered and their
// count exceeds 0
if (S.charAt(c) == '(' &&
count++ > 0)
// Include the character
res += S.charAt(c);
// If closing parentheses 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 parentheses is
# encountered and their
# count exceeds 0
if (c == '(' and count > 0):
# Include the character
res += c
# If closing parentheses 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 parentheses is
// encountered and their
// count exceeds 0
if (S[c] == '(' &&
count++ > 0)
// Include the character
res += S[c];
// If closing parentheses is
// encountered and their
// count is less than count
// of opening parentheses
if (S[c] == ')' &&
count-- > 1)
// Include the character
res += S[c];
}
// 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 parentheses is
// encountered and their
// count exceeds 0
if (S.charAt(c) == '(' &&
count++ > 0)
// Include the character
res += S.charAt(c);
// If closing parentheses 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>
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 string.
The Optimal approach to remove the outermost parentheses from a string can be achieved using a simple algorithm that keeps track of the number of opening and closing parentheses encountered. Here is an optimal approach:
- Initialize two variables, open_count and close_count, to zero
- Initialize an empty string called result.
- Loop through each character c in the input string s.
- If c is an opening parenthesis, increment open_count.
- If c is a closing parenthesis, increment close_count.
- If open_count and close_count are equal and greater than zero, this means that we have encountered a complete pair of opening and closing parentheses, so we can add the substring between them to the result string.
- Reset open_count and close_count to zero.
- Return the result string.
Here is an implementation of this algorithm:
C++
// C++ Program for the above approach
#include <iostream>
#include <string>
using namespace std;
// function to remove outer parentheses
string removeOuterParentheses(string s) {
int openCount = 0;
int closeCount = 0;
string result = "";
int start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s[i];
if (c == '(') {
openCount++;
} else if (c == ')') {
closeCount++;
}
if (openCount == closeCount) {
result += s.substr(start+1, i-start-1);
start = i+1;
}
}
// return the output string(result)
return result;
}
// driver program to test above function
int main() {
// Example 1
string s1 = "(()())(())()";
cout << removeOuterParentheses(s1) << endl;
// Example 2
string s2 = "()()(()())(()())";
cout << removeOuterParentheses(s2) << endl;
// Example 3
string s3 = "((()))(())";
cout << removeOuterParentheses(s3) << endl;
return 0;
}
Java
public class Main {
public static String removeOuterParentheses(String s) {
int openCount = 0;
int closeCount = 0;
String result = "";
int start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
openCount++;
} else if (c == ')') {
closeCount++;
}
if (openCount == closeCount) {
result += s.substring(start+1, i);
start = i+1;
}
}
return result;
}
public static void main(String[] args) {
// Example 1
String s1 = "(()())(())()";
System.out.println(removeOuterParentheses(s1));
// Example 2
String s2 = "()()(()())(()())";
System.out.println(removeOuterParentheses(s2));
// Example 3
String s3 = "((()))(())";
System.out.println(removeOuterParentheses(s3));
}
}
// This code is contributed by Sundaram
Python3
def remove_outer_parentheses(s):
open_count = 0
close_count = 0
result = ""
start = 0
for i, c in enumerate(s):
if c == "(":
open_count += 1
elif c == ")":
close_count += 1
if open_count == close_count:
result += s[start+1:i]
start = i+1
return result
# Driver code
if __name__ == "__main__":
# Example 1
s1 = "(()())(())()"
print(remove_outer_parentheses(s1))
# Example 2
s2 = "()()(()())(()())"
print(remove_outer_parentheses(s2))
# Example 3
s3 = "((()))(())"
print(remove_outer_parentheses(s3))
C#
// C# Program for the above approach
using System;
namespace RemoveOuterParentheses {
class Program {
// function to remove outer parentheses
static string RemoveOuterParentheses(string s)
{
int openCount = 0;
int closeCount = 0;
string result = "";
int start = 0;
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (c == '(') {
openCount++;
}
else if (c == ')') {
closeCount++;
}
if (openCount == closeCount) {
result += s.Substring(start + 1,
i - start - 1);
start = i + 1;
}
}
// return the output string(result)
return result;
}
// driver program to test above function
static void Main(string[] args)
{
// Example 1
string s1 = "(()())(())()";
Console.WriteLine(RemoveOuterParentheses(s1));
// Example 2
string s2 = "()()(()())(()())";
Console.WriteLine(RemoveOuterParentheses(s2));
// Example 3
string s3 = "((()))(())";
Console.WriteLine(RemoveOuterParentheses(s3));
}
}
}
// This code is contributed by sarojmcy2w
JavaScript
function remove_outer_parentheses(s) {
let open_count = 0;
let close_count = 0;
let result = "";
let start = 0;
for (let i = 0; i < s.length; i++) {
let c = s[i];
if (c == "(") {
open_count += 1;
} else if (c == ")") {
close_count += 1;
}
if (open_count == close_count) {
result += s.slice(start + 1, i);
start = i + 1;
}
}
return result;
}
// Driver code
// Example 1
let s1 = "(()())(())()";
console.log(remove_outer_parentheses(s1));
// Example 2
let s2 = "()()(()())(()())";
console.log(remove_outer_parentheses(s2));
// Example 3
let s3 = "((()))(())";
console.log(remove_outer_parentheses(s3));
Output()()()
()()()()
(())()
This approach has a time complexity of O(n), where n is the length of the input string s. It uses constant space, except for the output string, which is proportional to the number of valid parentheses pairs in s.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read