[
brackets
string
stack
]
Leetcode 1021. Remove Outermost Parentheses
Problem statement
https://leetcode.com/problems/remove-outermost-parentheses/
Solution
Just traverse string and check balance, when it is zero add to result.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def removeOuterParentheses(self, S):
res, bal, lft = [], 0, 0
for rgh in range(len(S)):
bal += (S[rgh] == "(") * 2 - 1
if bal == 0:
res += [i for i in S[lft + 1:rgh]]
lft = rgh + 1
return "".join(res)