VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-the-string-obtained-after-removal-of-outermost-parentheses/

⇱ Print the string obtained after removal of outermost parentheses - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print the string obtained after removal of outermost parentheses

Last Updated : 23 Jul, 2025

Given a valid parenthesis string str consisting of lowercase alphabets, opening, and closing brackets, the task is to find the string by removing the outermost enclosing brackets such that the string remains a valid parenthesis string.

Examples: 

Input: S = "(((a)(bcd)(e)))"
Output: (a)(bcd)(e)
Explanation: 
The outermost enclosing brackets are: { S[0], S[1], S[13], S[14] }. 
Removing the outermost enclosing brackets from str modifies str to "(a)(bcd)(e)". 
Therefore, the required output is (a)(bcd)(e).

Input: str = "((ab)(bc))d"
Output: ((ab)(bc))d
Explanation: 
Since no outermost enclosing brackets present in the string. Therefore, the required output is ((ab)(bc))d

Approach:The idea is to iterate over the characters of the string and count the number of consecutive opening parenthesis and closing parenthesis from both ends of the string respectively. Then, iterate over the characters present in the inner string and count the number of opening brackets needed to balance out the string. Follow the steps below to solve the problem:

Follow the below steps to solve the problem:

  • Initialize a variable, say cnt = 0, to store the count of valid parenthesis such that str[cnt] == '(' and str[N - cnt - 1] == ')'.
  • To balance the inner parenthesis of the string by the outer parenthesis, traverse the substring {str[cnt], ..., str[N - cnt - 1]} and count the minimum opening or closing parenthesis required to balance the inner substring say, cntMinpar.
  • Finally, update the cnt += cntMinPair and print the substring { str[cnt], ..., str[N - cnt] }.

Below is the implementation of the above approach:


Output: 
((a)b)(c)

 

Time Complexity: O(N)
Auxiliary Space: O(1)
 

Comment