Remove Outermost Parentheses - Problem

Imagine you have a string of parentheses that represents nested structures, like "(()())(())". Your task is to remove the outermost layer of parentheses from each independent group while keeping the inner structure intact.

A valid parentheses string is either:

  • Empty string ""
  • "(" + A + ")" where A is valid
  • A + B where both A and B are valid

A valid string is primitive if it cannot be split into two non-empty valid strings. For example, "(())" is primitive, but "()()" is not (can be split into "()" + "()").

Goal: Given a valid parentheses string, find all primitive components and remove their outermost parentheses.

Example: "(()())(())" has two primitives: "(()())" and "(())". After removing outer parentheses: "()()" + "()" = "()()()"

Input & Output

example_1.py โ€” Basic Case
$ Input: "(()())(())"
โ€บ Output: "()()()"
๐Ÿ’ก Note: The input has two primitive groups: "(()())" and "(())". Removing outer parentheses from first gives "()()" and from second gives "()". Combined result: "()()()".
example_2.py โ€” Simple Primitives
$ Input: "()()"
โ€บ Output: ""
๐Ÿ’ก Note: The input has two primitive groups: "()" and "()". Each primitive has only outer parentheses, so removing them leaves empty strings. Combined result: "".
example_3.py โ€” Nested Structure
$ Input: "(()(()))"
โ€บ Output: "()(())"
๐Ÿ’ก Note: The input is a single primitive group "(()(()))". Removing the outermost parentheses gives "()(())", which preserves the inner nested structure.

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s[i] is either '(' or ')'
  • s is guaranteed to be a valid parentheses string

Visualization

Tap to expand
๐Ÿช† Russian Nesting Dolls AnalogyFirst Doll Set: (()())OUTER( )( )Remove outer โ†’ ( ) ( )Second Doll Set: (())OUTER( )Remove outer โ†’ ( )Algorithm Visualization:Input: ( ( ) ( ) ) ( ( ) )Depth:1212101210Action:SKIPKEEPKEEPKEEPKEEPSKIPSKIPKEEPKEEPSKIPResult: ( ) ( ) ( )"()()()"
Understanding the Visualization
1
Identify Doll Sets
Each primitive group is a complete set of nested dolls
2
Track Nesting Depth
Count how deep you are in the current doll set
3
Remove Outer Shell
When depth is 1, you're touching the outermost doll - skip it
4
Keep Inner Dolls
When depth > 1, you're at inner dolls - keep them
Key Takeaway
๐ŸŽฏ Key Insight: Use depth tracking to identify outermost parentheses in a single pass - when depth equals 1, you're at the outer shell that needs to be removed!
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
89.3K Views
Medium Frequency
~12 min Avg. Time
2.8K 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