EasyNo. 1021

Remove Outermost Parentheses — LeetCode 1021 Python Solution

Pattern
Stack
Topics
Stack, String
Reading time
3 min

The 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.

Example

Input
s = "(()())(())"
Output
"()()()"
Explanation
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".

Python solution

PythonSolution
class Solution:
    def removeOuterParentheses(self, s: str) -> str:
        ans = []
        cnt = 0
        for c in s:
            if c == '(':
                cnt += 1
                if cnt > 1:
                    ans.append(c)
            else:
                cnt -= 1
                if cnt > 0:
                    ans.append(c)
        return ''.join(ans)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1021. Remove Outermost Parentheses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0020Valid ParenthesesEasy
0071Simplify PathMedium
0224Basic CalculatorHard
0227Basic Calculator IIMedium
0331Verify Preorder Serialization of a Binary TreeMedium
0385Mini ParserMedium

Frequently asked questions

How hard is LeetCode 1021. Remove Outermost Parentheses?

LeetCode 1021. Remove Outermost Parentheses is rated Easy on LeetCode.

What is the time complexity of LeetCode 1021. Remove Outermost Parentheses?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1021. Remove Outermost Parentheses?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1021. Remove Outermost Parentheses cover?

LeetCode 1021. Remove Outermost Parentheses is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.