Pankaj Tanwar
Published on

Remove Outermost Parentheses.

––– views

Problem of the day - Remove Outermost Parentheses

Tag - Easy

A valid parentheses string is either empty "", "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.

  • For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings.

Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.

Example 1:

Input: s = "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()".


Description is pretty much clear. So, we just need to keep on tracking of the end of each valid sub-parentheses and skip the first and last element of it.

Algorithm is a bit tricky. Skipping first and last element of the valid sub-parentheses requires some extra attention.

Well, let's boogie!

class Solution {
public:
string removeOuterParentheses(string s) {
int count = 0;
string res = "";
for(char c: s) {
if(count == 0) {
count += (c == '(' ? 1 : -1);
} else {
count += (c == '(' ? 1 : -1);
if(count != 0) {
res += c;
}
}
}
return res;
}
};

I don't think, code requires some extra explanation. Still, if you feel, I am missing on something, feel free to reach out to me


I welcome your suggestions to improve it further!


Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.


You might like previous editions of my coding diary