Remove Outermost Parentheses
MediumTrack depth; skip the outer layer
Problem
Given a valid parentheses string, remove the outermost pair of every primitive part and return the result.
Track nesting depth; keep a bracket only when it isn't the outermost of its group.
The idea
Walk the string keeping a running depth. An opening bracket at depth 0 and a closing bracket returning to depth 0 are the outermost pair of a primitive, so skip exactly those and copy everything else.
The trick
- Append '(' only when depth is already above 0; append ')' only when depth will stay above 0.
- Increment after the check on '(' and decrement before the check on ')'.
- O(n) with one counter.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — (()())(()) Values: 0.
1depth=0; out=''2for c: if c=='(' : if depth>0 out+='('; depth++3 else: depth--; if depth>0 out+=')'4return outInput
- array
- [0]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- s = "(()())(())"
- Output:
- "()()()"
- Explanation:
- Strip the outer layer of each primitive group.
Example 2
- Input:
- s = "(())"
- Output:
- "()"
- Explanation:
- Outer pair removed → "()".
Example 3
- Input:
- s = "()()"
- Output:
- ""
- Explanation:
- Each group's outer pair goes → empty.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.