Remove Outermost Parentheses

A valid parentheses string is empty, `"(" + A + ")"`, or `A + B`, where `A` and `B` are valid. A non-empty valid string is primitive if it cannot be split into two non-empty valid strings. Any valid string `s` can be written uniquely as `P1 + P2 + ... + Pk` with each `Pi` primitive. Given a valid string `s`, remove the outermost pair of parentheses of every primitive in that decomposition and return the result.

30:00

Remove Outermost Parentheses
easy
Free written solution
Topics
Companies

A valid parentheses string is empty, "(" + A + ")", or A + B, where A and B are valid. A non-empty valid string is primitive if it cannot be split into two non-empty valid strings. Any valid string s can be written uniquely as P1 + P2 + ... + Pk with each Pi primitive. Given a valid string s, remove the outermost pair of parentheses of every primitive in that decomposition and return the result.

Example 1:
Input: {"s":"(()())(())"}
Output: ()()()
Constraints:
  • 1≤s.length≤1051 \leq s.\text{length} \leq 10^5

  • s[i] is either '(' or ')'.

  • s is a valid parentheses string.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"(()())(())"}

s by nesting depth

depth 0

(

0

(

1

)

2

(

3

)

4

)

5

(

6

(

7

)

8

)

9

■ depth 0: outer pair, removed■ inner, keptshaded columns = one primitive

Each character sits at its nesting depth. The ones on the ground line (depth 0) are the outer pair of a primitive; everything above it is kept.

output (inner characters, in order)

length 0

nothing kept yet

primitives closed 0
outer removed 0
Variables
VariableValue
depth0
out
DepthFunction Call
Stack empty
0/11