Remove the Outermost Parentheses From Every Primitive Group

Implement removeOuterParentheses

A string is a "primitive" parentheses group if it's non-empty, balanced, and never dips back to depth 0 in the middle — s is always a sequence of these primitive groups placed back to back. Given a valid parentheses string s, remove the outermost parentheses of every primitive group and return what's left. Tracking depth as you scan and slicing out each group once its depth returns to 0 works, but building each slice separately means an extra pass through the substring boundaries. The faster approach skips slicing entirely: classify each character in a single pass by checking depth right before incrementing (for an opener) or right after decrementing (for a closer) — a depth of exactly 0 at that check means the character is an outermost paren to drop, anything else means it's an inner paren to keep.

Example 1:

Input: s = "(()())(())"

Output: "()()()"

Example 2:

Input: s = "()()"

Output: ""

Example 3:

Input: s = "(()(()))(())"

Output: "()(())()"

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 5 × 10⁴
  • s consists only of '(' and ')'
  • s is a valid parentheses string

s =

(()())(())