↓Skip to main content
  1. LeetCode/

LeetCode 1021: Remove Outermost Parentheses

·1 min· ·
LeetCode Easy String Stack Bracket-Sequences
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-27

  • Submissions: Wrong Answer → Accepted

Approach
#

With a single bracket type the stack only ever holds (, so a depth counter suffices (Stack Template 1). On (, keep it only if the depth was already > 0, then increment; on ), decrement first and keep it only if the depth is still > 0. That strips the outer pair of every primitive.

My Attempts
#

Attempt 1 used a stack to find each primitive and temp[1:-1] to strip its ends, which was right, but it forgot the return; adding it passed.

Solution
#

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

Complexity
#

Time O(n), space O(n) (output).

Mistakes to Avoid
#

  • Check ( before incrementing and ) after decrementing.

Interview Explanation
#

With one bracket type I count depth instead of using a stack: an opening bracket is kept when the depth is already positive, a closing one when the depth stays positive after decrementing, removing each primitive’s outer pair. Time O(n).

Related

LeetCode 844: Backspace String Compare
·2 mins
LeetCode Easy Two-Pointers String Stack Simulation
LeetCode 844 note: simulate backspaces with a stack; for O(1) space, walk from the end and count how many characters each # skips
LeetCode 1002: Find Common Characters
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 1002 note: count each word and intersect all Counters (minimum count per character), then expand
LeetCode 929: Unique Email Addresses
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 929 note: split at @, normalize only the local part (drop everything after +, remove dots), rejoin with the domain and collect in a set
LeetCode 944: Delete Columns to Make Sorted
·1 min
LeetCode Easy Array String Longest-Increasing-Subsequence
LeetCode 944 note: take each column with zip(*strs) and count the columns that are not non-decreasing
LeetCode 953: Verifying an Alien Dictionary
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 953 note: map letters to their alien index and compare each adjacent pair at the first differing character; with no difference, the shorter must come first
LeetCode 897: Increasing Order Search Tree
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Search-Tree
LeetCode 897 note: in-order traversal appending nodes to a right-only chain with left children cleared; keep the dummy separate from the moving tail