Remove Outermost Parentheses — LeetCode 1021 Python Solution
- Problem
- #1021
- Pattern
- Stack
- Reading time
- 3 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
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.