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 Parentheses INPUT s = "(()())(())" (()()) Primitive 1 Outer: ( ) (()) Primitive 2 Outer: ( ) Primitive Decomposition: (()()) + (()) Input String: "(()())(())" Length: 10 characters 2 primitive substrings ALGORITHM STEPS 1 Initialize Counter depth = 0, result = "" 2 Scan Each Char Track depth with counter 3 Skip Outer Parens '(' when depth=0, ')' to 0 4 Add Inner Parens Include all others Character Processing: Char Action Depth Add? ( 0-->1 1 NO ( 1-->2 2 OK ) 2-->1 1 OK ( 1-->2 2 OK ) 2-->1 1 OK ) 1-->0 0 NO ... (()) similar ... ... FINAL RESULT After removing outer parentheses: Primitive 1: (()()) --> ()() Remove outer ( ) Primitive 2: (()) --> () Remove outer ( ) Combined Result: ()() + () = ()()() Output: "()()()" OK - All outer parens removed! Length: 10 --> 6 (4 removed) Key Insight: Use a depth counter to track nesting level. A '(' at depth 0 starts a new primitive (skip it), and a ')' that returns depth to 0 ends a primitive (skip it too). All other characters are inner parentheses and should be included in the result. Time: O(n), Space: O(n) TutorialsPoint - Remove Outermost Parentheses | Optimal Solution (Counter-Based)
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