Strings Parentheses and nesting

133. Remove Outermost Parentheses

Easy

You are given a string s made of ( and ), and its parentheses are properly nested: every ( is closed by a later ), and every ) closes an earlier (.

A properly nested string splits into primitive pieces. Each piece is properly nested on its own, and it cannot be cut into two smaller properly nested pieces. For example, (())() splits into (()) and ().

Remove the outermost pair of parentheses from every primitive piece, and return what is left, in order.

Answers are shown in double quotes, so an empty answer shows as "".

Example 1

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

Output: "()()(())"

Explanation: The pieces are (()()), ((())) and (). Without their outer pairs they become ()(), (()) and nothing, and these are joined in order.

Example 2

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

Output: "(()())"

Explanation: The whole string is one piece, so only its first and last characters go.

Example 3

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

Output: ""

Explanation: Each piece is a bare (). Its outer pair is all it holds, so nothing is left.

Check your understanding

Work out the answer for this input before you write any code.

s = "(()(()))()"

Constraints

  • 2 ≤ s.length ≤ 105
  • s holds only the characters ( and ), and it is properly nested.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.