Remove Outermost Parentheses Problem
Description
LeetCode Problem 1021.
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.
A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.
Given a valid parentheses string s, consider its primitive decomposition: s = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.
Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.
Example 1:
Input: s = "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input: s = "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:
Input: s = "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
Constraints:
1 <= s.length <= 10^5s[i]is either'('or')'.sis a valid parentheses string.
Solution
Approach: Count the Depth
We do not need to split s into its primitive parts explicitly. Keep a counter depth of how many parentheses are open, and scan the string once:
- For
'(': ifdepthis0, this parenthesis opens a new primitive part, so it is an outermost one and we skip it. Otherwise we keep it. Then increasedepth. - For
')': first decreasedepth. If it is now0, this parenthesis closes the current primitive part, so we skip it. Otherwise we keep it.
The order of "check, then update" matters: an opening parenthesis is outer when the depth before it is 0, and a closing one is outer when the depth after it is 0. Since s is valid, depth never goes below 0.
For example, in "(()())(())" the characters at depth 0 → 1 and 1 → 0 are positions 0, 5, 6 and 9; dropping them leaves "()()()".
Complexity: O(n) time and O(n) space for the result.
class Solution:
def removeOuterParentheses(self, s: str) -> str:
result = []
depth = 0 # how many parentheses are open before the current character
for c in s:
if c == '(':
if depth > 0: # not the opening parenthesis of a primitive part
result.append(c)
depth += 1
else:
depth -= 1
if depth > 0: # not the closing parenthesis of a primitive part
result.append(c)
return ''.join(result)