Remove Outermost Parentheses
LeetCode 1021 · Easy · solution, intuition & step-by-step walkthrough
Depth returns to 0 ⇒ a primitive ends.
This is how I solved Remove Outermost Parentheses (LeetCode 1021), an easy problem from the Parentheses / Bracket Matching pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
A primitive part ends each time the open-bracket count drops back to zero. Split the string at those points and strip the first and last character of each part.
Approach
- 1
Track depth with a stack; record indices where it becomes empty.
- 2
Slice the string into primitive parts.
- 3
Drop each part's outer pair and join.
How I solved it
Split at depth zeroPythonO(n) time
class Solution:
def removeOuterParentheses(self, s: str) -> str:
#capture the index when stack got empty
indexes=[]
stack=[]
for i in range(len(s)):
if s[i]=="(":
stack.append(s[i])
else:
stack.pop()
if len(stack)==0:
indexes.append(i)
parts=[]
i=0
#0:5+1
#5+1:9+1
#
for index in indexes:
parts.append(s[i:index+1])
i=index+1
res=[]
for part in parts:
res.append(part[1:len(part)-1])
return "".join(res)
Remove Outermost Parentheses — FAQ
What is the intuition behind Remove Outermost Parentheses?
A primitive part ends each time the open-bracket count drops back to zero. Split the string at those points and strip the first and last character of each part.
How do you solve Remove Outermost Parentheses (LeetCode 1021)?
1. Track depth with a stack; record indices where it becomes empty. 2. Slice the string into primitive parts. 3. Drop each part's outer pair and join.
What is the time and space complexity of Remove Outermost Parentheses?
Time: O(n). Space: O(n). (Accepted approach: Split at depth zero.)
What are common mistakes in Remove Outermost Parentheses?
A depth counter alone (no stack) is enough and avoids extra memory.