Remove the outermost parentheses of every primitive component.
Problem Statement
Examples
Input: s = "(()())(())"
Output: "()()()"
Explanation: Outer parentheses of each primitive block are removed yielding "()()()".
Input: s = "(()())(())(()(()))"
Output: "()()()()(())"
Explanation: Outer parentheses of each primitive block are removed yielding "()()()()(())".
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
Editorial & Approach
Problem Overview & Intuition
A primitive valid parenthesis string has balance > 0 inside, and returns to balance 0 only at the outermost closing parenthesis. By maintaining a balance counter opened, we filter out the outermost ( at opened = 0 and outermost ) at opened = 1.
Step-by-Step Approach
- Initialize
res = ""andopened = 0. - Iterate through each character
cins. - If
c === "(", ifopened > 0append tores, thenopened++. - If
c === ")", ifopened > 1append tores, thenopened--. - Return
res.
Optimal Implementation (JavaScript)
function removeOuterParentheses(s) {
let res = '', opened = 0;
for (let c of s) {
if (c === '(' && opened++ > 0) res += c;
if (c === ')' && opened-- > 1) res += c;
}
return res;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Single primitive component: returns inner parentheses.
- Empty inner component "()()": returns empty string "".
- Deeply nested parentheses.