Remove Outermost Parentheses - Problem

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 = P₁ + P₂ + ... + Pₖ, where Pᵢ are primitive valid parentheses strings.

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

Input & Output

Example 1 — Two Primitives
$ Input: s = "(()())(())"
Output: "()()(())"
💡 Note: Input has two primitives: "(()())" and "(())". Removing outer parentheses gives "()()" + "()" = "()()(())".
Example 2 — Single Primitive
$ Input: s = "(()())"
Output: "()()"
💡 Note: Input is one primitive substring. Remove the outermost '(' and ')' to get "()()".
Example 3 — Simple Cases
$ Input: s = "()()"
Output: ""
💡 Note: Two primitives "()" and "()". Each becomes empty after removing outer parentheses, so result is empty string.

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either '(' or ')'
  • s is a valid parentheses string

Visualization

Tap to expand
Remove Outermost ParenthesesInput: "(()())(())"(()())(()Primitive 1Primitive 2Remove Red (Outermost):()()(Result: "()()(())"
Understanding the Visualization
1
Input
Valid parentheses string with primitive components
2
Identify Primitives
Find complete primitive substrings using balance counting
3
Remove Outer
Skip first and last parentheses of each primitive
Key Takeaway
🎯 Key Insight: Track nesting depth to distinguish between inner and outer parentheses
Asked in
Amazon 15 Facebook 12 Google 8
125.0K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen