Explorer
Data Structures & Algorithms

Remove the outermost parentheses of every primitive component.

Problem Statement

A valid parentheses string is either empty `""`, `"(" + A + ")"`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. Return `s` after removing the outermost parentheses of every primitive component in the primitive decomposition of `s`.

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

šŸ’” Hint 1: Track the balance of open parentheses with a counter opened. šŸ’” Hint 2: An opening parenthesis belongs to the inner content if opened > 0 before incrementing. šŸ’” Hint 3: A closing parenthesis belongs to the inner content if opened > 1 before decrementing.

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

  1. Initialize res = "" and opened = 0.
  2. Iterate through each character c in s.
  3. If c === "(", if opened > 0 append to res, then opened++.
  4. If c === ")", if opened > 1 append to res, then opened--.
  5. 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

Time Complexity O(N) — single pass over the string.
Space Complexity O(N) — for the resulting string.

Edge Cases & Corner Traps Handled

  • Single primitive component: returns inner parentheses.
  • Empty inner component "()()": returns empty string "".
  • Deeply nested parentheses.

Remove Outermost Parentheses

Easy
A valid parentheses string is either empty `""`, `"(" + A + ")"`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. Return `s` after removing the outermost parentheses of every primitive component in the primitive decomposition of `s`.
Example Scenarios
1Example 1
Input: s = "(()())(())"
Output: "()()()"
Explanation:

Outer parentheses of each primitive block are removed yielding "()()()".

2Example 2
Input: s = "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:

Outer parentheses of each primitive block are removed yielding "()()()()(())".

Editor
Loading Editor...
s =
"(()())(())"
Output:Click "Run" above to execute and verify your code here.
()()()