Peel the Outer Layer

EasyStack

Problem

A balanced string s of ( and ) can be cut uniquely into groups: non-empty balanced pieces that cannot themselves be split into two balanced pieces. For example (())()((())) is the groups (()), () and ((())).

Remove the outermost pair of parentheses from every group and return the concatenation of what remains.

Example 1

Input:
s = "(())()((()))"
Output:
"()(())"

(()) → (), () → empty, ((())) → (()). Joined: ()(()).

Example 2

Input:
s = "()()"
Output:
""

Constraints

  • 0 ≤ s.length ≤ 10^5
  • s is balanced

Hint

Show the first hint

A group ends exactly when the matching stack becomes empty again.

Walkthrough

How to approach it

01Clarify before coding

  • Is s always balanced? Yes.
  • Is a group like "()" peeled to nothing? Yes, it contributes the empty string.

02Brute force

Find each group's end by rescanning with a counter, slice the group, strip its first and last characters, and concatenate with repeated string additions.

Cost: O(n) scanning, but repeated immutable concatenation can push it to O(n²).

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.